Просмотр исходного кода

Merge branch 'master' into fix/not-set-state-of-input-form

yusuketk 5 лет назад
Родитель
Сommit
659b1dee6f
100 измененных файлов с 2796 добавлено и 769 удалено
  1. 25 3
      CHANGES.md
  2. 4 4
      README.md
  3. 2 2
      bin/github-actions/update-readme.sh
  4. 1 1
      config/env.dev.js
  5. 1 1
      config/logger/config.dev.js
  6. 0 4
      config/webpack.common.js
  7. 4 2
      docker/README.md
  8. 6 5
      package.json
  9. 1 1
      resource/cdn-manifests.js
  10. 4 1
      resource/locales/en_US/admin/admin.json
  11. 37 7
      resource/locales/en_US/translation.json
  12. 3 0
      resource/locales/ja_JP/admin/admin.json
  13. 35 4
      resource/locales/ja_JP/translation.json
  14. 4 1
      resource/locales/zh_CN/admin/admin.json
  15. 30 7
      resource/locales/zh_CN/translation.json
  16. 3 2
      src/client/js/admin.jsx
  17. 5 3
      src/client/js/app.jsx
  18. 5 3
      src/client/js/base.jsx
  19. 65 2
      src/client/js/components/Admin/App/MailSetting.jsx
  20. 7 7
      src/client/js/components/Admin/ElasticsearchManagement/ElasticsearchManagement.jsx
  21. 12 8
      src/client/js/components/Admin/ElasticsearchManagement/RebuildIndexControls.jsx
  22. 4 4
      src/client/js/components/Admin/ExportArchiveDataPage.jsx
  23. 5 5
      src/client/js/components/Admin/ImportData/GrowiArchive/ImportForm.jsx
  24. 66 0
      src/client/js/components/Admin/Security/DeleteAllShareLinksModal.jsx
  25. 8 1
      src/client/js/components/Admin/Security/SecurityManagement.jsx
  26. 147 0
      src/client/js/components/Admin/Security/ShareLinkSetting.jsx
  27. 139 0
      src/client/js/components/OutsideShareLinkModal.jsx
  28. 4 1
      src/client/js/components/Page.jsx
  29. 29 16
      src/client/js/components/Page/CopyDropdown.jsx
  30. 38 11
      src/client/js/components/Page/PageManagement.jsx
  31. 100 0
      src/client/js/components/Page/PageShareManagement.jsx
  32. 59 0
      src/client/js/components/Page/ShareLinkAlert.jsx
  33. 0 1
      src/client/js/components/PageCreateModal.jsx
  34. 0 1
      src/client/js/components/PageDuplicateModal.jsx
  35. 26 1
      src/client/js/components/PageEditor/CodeMirrorEditor.jsx
  36. 353 0
      src/client/js/components/PageEditor/LinkEditModal.jsx
  37. 3 3
      src/client/js/components/PageEditor/MarkdownDrawioUtil.js
  38. 48 0
      src/client/js/components/PageEditor/MarkdownLinkUtil.js
  39. 7 2
      src/client/js/components/PageHistory.jsx
  40. 0 2
      src/client/js/components/PagePathAutoComplete.jsx
  41. 1 1
      src/client/js/components/PageStatusAlert.jsx
  42. 272 0
      src/client/js/components/ShareLinkForm.jsx
  43. 79 0
      src/client/js/components/ShareLinkList.jsx
  44. 3 1
      src/client/js/components/Sidebar.jsx
  45. 10 1
      src/client/js/components/Sidebar/SidebarContents.jsx
  46. 3 3
      src/client/js/components/Sidebar/SidebarNav.jsx
  47. 0 1
      src/client/js/hackmd-agent.js
  48. 147 0
      src/client/js/models/Linker.js
  49. 13 0
      src/client/js/services/AdminAppContainer.js
  50. 29 0
      src/client/js/services/AdminGeneralSecurityContainer.js
  51. 19 0
      src/client/js/services/AdminSocketIoContainer.js
  52. 3 0
      src/client/js/services/AppContainer.js
  53. 18 16
      src/client/js/services/PageContainer.js
  54. 9 5
      src/client/js/services/SocketIoContainer.js
  55. 0 16
      src/client/js/util/interceptor/drawio-interceptor.js
  56. 1 6
      src/client/styles/scss/_layout_kibela.scss
  57. 8 0
      src/client/styles/scss/_linkedit-preview.scss
  58. 23 10
      src/client/styles/scss/_on-edit.scss
  59. 12 0
      src/client/styles/scss/_override-bootstrap-variables.scss
  60. 2 0
      src/client/styles/scss/_override-bootstrap.scss
  61. 4 4
      src/client/styles/scss/_search.scss
  62. 12 0
      src/client/styles/scss/_sharelink.scss
  63. 1 0
      src/client/styles/scss/_sidebar.scss
  64. 2 0
      src/client/styles/scss/style-app.scss
  65. 11 11
      src/client/styles/scss/theme/_apply-colors-light.scss
  66. 8 8
      src/client/styles/scss/theme/_apply-colors.scss
  67. 15 14
      src/client/styles/scss/theme/default.scss
  68. 2 2
      src/server/crowi/express-init.js
  69. 57 29
      src/server/crowi/index.js
  70. 0 11
      src/server/events/search.js
  71. 0 11
      src/server/middlewares/auto-reconnect-to-config-pubsub.js
  72. 11 0
      src/server/middlewares/auto-reconnect-to-s2s-msg-server.js
  73. 46 0
      src/server/middlewares/certify-shared-file.js
  74. 31 0
      src/server/middlewares/certify-shared-page.js
  75. 6 0
      src/server/middlewares/login-required.js
  76. 1 0
      src/server/models/index.js
  77. 45 35
      src/server/models/page.js
  78. 1 1
      src/server/models/revision.js
  79. 38 0
      src/server/models/share-link.js
  80. 6 3
      src/server/models/vo/s2s-message.js
  81. 0 13
      src/server/routes/admin.js
  82. 66 17
      src/server/routes/apiv3/app-settings.js
  83. 4 4
      src/server/routes/apiv3/export.js
  84. 4 4
      src/server/routes/apiv3/import.js
  85. 1 0
      src/server/routes/apiv3/index.js
  86. 72 1
      src/server/routes/apiv3/security-setting.js
  87. 212 0
      src/server/routes/apiv3/share-links.js
  88. 0 5
      src/server/routes/hackmd.js
  89. 7 4
      src/server/routes/index.js
  90. 56 35
      src/server/routes/page.js
  91. 18 93
      src/server/routes/revision.js
  92. 17 16
      src/server/service/app.js
  93. 14 8
      src/server/service/config-loader.js
  94. 18 16
      src/server/service/config-manager.js
  95. 0 14
      src/server/service/config-pubsub/handlable.js
  96. 0 195
      src/server/service/config-pubsub/nchan.js
  97. 13 13
      src/server/service/customize.js
  98. 13 13
      src/server/service/mail.js
  99. 29 0
      src/server/service/page.js
  100. 13 13
      src/server/service/passport.js

+ 25 - 3
CHANGES.md

@@ -1,6 +1,17 @@
 # CHANGES
 
-## v4.1.0-RC
+## v4.1.1-RC
+
+* Feature: External share link
+* Feature: Create/edit linker with GUI
+* Improvement: Optimize some features that operate revision data
+    * Page history
+    * Renaming pages
+    * Deleting pages
+* Fix: "Append params" switch of CopyDropdown does not work when multiple CopyDropdown instance exists\
+
+
+## v4.1.0
 
 ### BREAKING CHANGES
 
@@ -11,21 +22,32 @@ Upgrading Guide: <https://docs.growi.org/en/admin-guide/upgrading/41x.html>
 
 ### Updates
 
-* Feature: Config synchronization for multiple GROWI Apps
+* Feature: Server settings synchronization for multiple GROWI Apps
+* Feature: Page status alert synchronization for multiple GROWI Apps
 * Feature: Smooth scroll for anchor links
 * Feature: Mirror Mode with [Konami Code](https://en.wikipedia.org/wiki/Konami_Code)
 * Improvement: Determine whether the "In Use" badge is displayed or not by attachment ID
+* Improvement: draw.io under NO_CDN environment
+* Fix: Deleting/renaming with recursive option affects pages that are inaccessible to active users
+* Fix: DrawioModal cuts without beginning/ending line
 * Fix: New settings of SMTP and AWS SES are not reflected when server is running
+* Fix: Sidebar layout broken when using Kibela layout
 * Support: Support Node.js v14
+* Support: Update libs
+    * mathjax
 
+## v4.0.11
 
+* Fix: Fab on search result page does not displayed
+* Fix: Adjust margin/padding for search result page
+* Fix: PageAlert broken
+    * Introduced by v4.0.9
 
 ## v4.0.10
 
 * Improvement: Adjust ToC height
 * Fix: Fail to rename/delete a page set as "Anyone with the link"
 
-
 ## v4.0.9
 
 * Feature: Detailed configurations for OpenID Connect

+ 4 - 4
README.md

@@ -111,11 +111,11 @@ See [confirmed versions](https://docs.growi.org/en/dev/startup/dev-env.html#set-
 
 |command|desc|
 |--|--|
-|`npm run build:prod`|Build the client|
-|`npm run server:prod`|Launch the server|
-|`npm start`|Invoke `npm run build:prod` and `npm run server:prod`|
+|`yarn run build:prod`|Build the client|
+|`yarn run server:prod`|Launch the server|
+|`yarn start`|Invoke `yarn run build:prod` and `yarn run server:prod`|
 
-For more info, see [GROWI Docs: List of npm Commands](https://docs.growi.org/en/dev/startup/launch.html#list-of-npm-commands).
+For more info, see [GROWI Docs: List of npm Commands](https://docs.growi.org/en/dev/startup-v2/launch.html#list-of-npm-commands).
 
 
 Documentation

+ 2 - 2
bin/github-actions/update-readme.sh

@@ -2,5 +2,5 @@
 
 cd docker
 
-sed -i -e "s/^\([*] \[\`\)[^\`]\+\(\`, \`4\.0\`, .\+\]\)\(.\+\/blob\/v\).\+\(\/docker\/Dockerfile.\+\)$/\1${RELEASE_VERSION}\2\3${RELEASE_VERSION}\4/" README.md
-sed -i -e "s/^\([*] \[\`\)[^\`]\+\(\`, \`4\.0-nocdn\`, .\+\]\)\(.\+\/blob\/v\).\+\(\/docker\/Dockerfile.\+\)$/\1${RELEASE_VERSION}-nocdn\2\3${RELEASE_VERSION}\4/" README.md
+sed -i -e "s/^\([*] \[\`\)[^\`]\+\(\`, \`4\.1\`, .\+\]\)\(.\+\/blob\/v\).\+\(\/docker\/Dockerfile.\+\)$/\1${RELEASE_VERSION}\2\3${RELEASE_VERSION}\4/" README.md
+sed -i -e "s/^\([*] \[\`\)[^\`]\+\(\`, \`4\.1-nocdn\`, .\+\]\)\(.\+\/blob\/v\).\+\(\/docker\/Dockerfile.\+\)$/\1${RELEASE_VERSION}-nocdn\2\3${RELEASE_VERSION}\4/" README.md

+ 1 - 1
config/env.dev.js

@@ -11,7 +11,7 @@ module.exports = {
   HACKMD_URI: 'http://localhost:3010',
   HACKMD_URI_FOR_SERVER: 'http://hackmd:3000',
   // DRAWIO_URI: 'http://localhost:8080/?offline=1&https=0',
-  // CONFIG_PUBSUB_SERVER_TYPE: 'nchan',
+  // S2SMSG_PUBSUB_SERVER_TYPE: 'nchan',
   PLUGIN_NAMES_TOBE_LOADED: [
     // 'growi-plugin-lsx',
     // 'growi-plugin-pukiwiki-like-linker',

+ 1 - 1
config/logger/config.dev.js

@@ -16,7 +16,7 @@ module.exports = {
   'growi:routes:login-passport': 'debug',
   'growi:middleware:safe-redirect': 'debug',
   'growi:service:PassportService': 'debug',
-  'growi:service:config-pubsub:*': 'debug',
+  'growi:service:s2s-messaging:*': 'debug',
   // 'growi:service:ConfigManager': 'debug',
   // 'growi:service:mail': 'debug',
   'growi:lib:search': 'debug',

+ 0 - 4
config/webpack.common.js

@@ -96,10 +96,6 @@ module.exports = (options) => {
             basenameAsNamespace: true,
           },
         },
-        { // see https://github.com/abpetkov/switchery/issues/120
-          test: /switchery\.js$/,
-          loader: 'imports-loader?module=>false,exports=>false,define=>false,this=>window',
-        },
         /*
          * File loader for supporting images, for example, in CSS files.
          */

+ 4 - 2
docker/README.md

@@ -10,8 +10,10 @@ GROWI Official docker image
 Supported tags and respective Dockerfile links
 ------------------------------------------------
 
-* [`4.0.0`, `4.0`, `4`, `latest` (Dockerfile)](https://github.com/weseek/growi/blob/v4.0.0/docker/Dockerfile)
-* [`4.0.0-nocdn`, `4.0-nocdn`, `4-nocdn`, `latest-nocdn` (Dockerfile)](https://github.com/weseek/growi/blob/v4.0.0/docker/Dockerfile)
+* [`4.1.0`, `4.1`, `4`, `latest` (Dockerfile)](https://github.com/weseek/growi/blob/v4.1.0/docker/Dockerfile)
+* [`4.1.0-nocdn`, `4.1-nocdn`, `4-nocdn`, `latest-nocdn` (Dockerfile)](https://github.com/weseek/growi/blob/v4.1.0/docker/Dockerfile)
+* [`4.0.11`, `4.0`(Dockerfile)](https://github.com/weseek/growi/blob/v4.0.11/docker/Dockerfile)
+* [`4.0.11-nocdn`, `4.0-nocdn` (Dockerfile)](https://github.com/weseek/growi/blob/v4.0.11/docker/Dockerfile)
 * [`3.8.0`, `3.8`, `3` (Dockerfile)](https://github.com/weseek/growi/blob/v3.8.0/docker/Dockerfile)
 * [`3.8.0-nocdn`, `3.8-nocdn`, `3-nocdn` (Dockerfile)](https://github.com/weseek/growi/blob/v3.8.0/docker/Dockerfile)
 

+ 6 - 5
package.json

@@ -1,6 +1,6 @@
 {
   "name": "growi",
-  "version": "4.1.0-RC",
+  "version": "4.1.1-RC",
   "description": "Team collaboration software using markdown",
   "tags": [
     "wiki",
@@ -137,10 +137,11 @@
     "passport-twitter": "^1.0.4",
     "react-card-flip": "^1.0.10",
     "react-image-crop": "^8.3.0",
+    "reconnecting-websocket": "^4.4.0",
     "redis": "^3.0.2",
     "rimraf": "^3.0.0",
     "slack-node": "^0.1.8",
-    "socket.io": "^2.0.3",
+    "socket.io": "^2.3.0",
     "stream-to-promise": "^2.2.0",
     "string-width": "^4.1.0",
     "swig-templates": "^2.0.2",
@@ -148,7 +149,7 @@
     "unzipper": "^0.10.5",
     "url-join": "^4.0.0",
     "validator": "^12.0.0",
-    "websocket": "^1.0.31",
+    "ws": "^7.3.1",
     "xss": "^1.0.6"
   },
   "devDependencies": {
@@ -203,7 +204,7 @@
     "lodash-webpack-plugin": "^0.11.5",
     "markdown-it": "^10.0.0",
     "markdown-it-blockdiag": "^1.1.1",
-    "markdown-it-drawio-viewer": "^1.2.0",
+    "markdown-it-drawio-viewer": "^1.3.0",
     "markdown-it-emoji": "^1.4.0",
     "markdown-it-footnote": "^3.0.1",
     "markdown-it-mathjax": "^2.0.0",
@@ -240,7 +241,7 @@
     "rs-i18n": "^0.0.9",
     "sass-loader": "^8.0.0",
     "simple-load-script": "^1.0.2",
-    "socket.io-client": "^2.0.3",
+    "socket.io-client": "^2.3.0",
     "sticky-events": "^3.1.3",
     "style-loader": "^1.0.0",
     "styled-components": "^5.0.1",

+ 1 - 1
resource/cdn-manifests.js

@@ -39,7 +39,7 @@ module.exports = {
     },
     {
       name: 'mathjax',
-      url: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js',
+      url: 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js',
       args: {
         async: true,
         integrity: '',

+ 4 - 1
resource/locales/en_US/admin/admin.json

@@ -26,7 +26,7 @@
     "enable_files_except_image": "Enabling this option will allow upload of any file type. Without this option, only image file upload is supported.",
     "attach_enable": "You can attach files other than image files if you enable this option.",
     "update": "Update",
-    "mail_settings": "Mail settings",
+    "mail_settings": "E-mail Settings",
     "smtp_used": "If you have SMTP settings, it will be used.",
     "smtp_but_aws": "If you do not have SMTP settings but AWS settings,  e-mails will be sent by SES.",
     "neihter_of": "If neither is selected, then no email will be sent.",
@@ -35,6 +35,9 @@
     "host": "Host",
     "port": "Port",
     "user": "User",
+    "initialize_mail_settings": "initialize e-mail settings",
+    "initialize_mail_modal_header": "Initialize e-mail settings",
+    "confirm_to_initialize_mail_settings": "You can't restore to the current settings. Are you sure you want to initialize e-mail settings?",
     "aws_settings": "AWS settings",
     "aws_access": "This is for AWS settings. If you complete AWS settings, file upload function, profile picture function etc will be enabled.",
     "no_smtp_setting": "If you do not have SMTP settings, e-mails will be sent via SES. You need to verify from e-mail address and production settings.",

+ 37 - 7
resource/locales/en_US/translation.json

@@ -19,6 +19,7 @@
   "Tag": "Tag",
   "Tags": "Tags",
   "New": "New",
+  "Close": "Close",
   "Shortcuts": "Shortcuts",
   "eg": "e.g.",
   "add": "Add",
@@ -47,12 +48,16 @@
   "History": "History",
   "Presentation Mode": "Presentation",
   "Not available for guest": "Not available for guest",
+  "Create Archive Page": "Create Archive Page",
+  "File type": "File type",
+  "Include Attachment File": "Include Attachment File",
+  "Include Comment": "Include Comment",
+  "Include Subordinated Page": "Include Subordinated Page",
   "username": "Username",
   "Created": "Created",
   "Last updated": "Updated",
   "Last_Login": "Last login",
   "Share": "Share",
-  "Share Link": "Share Link",
   "Markdown Link": "Markdown Link",
   "Create/Edit Template": "Create/Edit template page",
   "Go to this version": "View this version",
@@ -189,6 +194,25 @@
     "password_is_not_set": "Password is not set"
   },
   "security_settings": "Security settings",
+  "share_links": {
+    "Shere this page link to public": "Shere this page link to public",
+    "share_link_list": "Share link list",
+    "share_link_management": "Share Link Management",
+    "No_share_links":"No share links",
+    "Share Link": "Share Link",
+    "Page Path": "Page Path",
+    "share_link_notice":"remove all share links",
+    "delete_all_share_links":"Delete all share links",
+    "expire": "Expiration",
+    "Days": "Days",
+    "Custom": "Custom",
+    "description": "description",
+    "enter_desc": "Enter description",
+    "Unlimited": "unlimited",
+    "Issue": "Issue",
+    "share_settings" :"Share settings",
+    "Invalid_Number_of_Date" : "You entered invalid value"
+  },
   "API Settings": "API settings",
   "API Token Settings": "API token settings",
   "Current API Token": "Current API token",
@@ -207,8 +231,8 @@
     "Copy to clipboard": "Copy to clipboard",
     "Page path": "Page path",
     "Page URL": "Page URL",
-    "Parmanent link": "Parmanent link",
-    "Page path and parmanent link": "Page path and parmanent link",
+    "Permanent link": "Permanent link",
+    "Page path and permanent link": "Page path and permanent link",
     "Markdown link": "Markdown link"
   },
   "search_help": {
@@ -249,7 +273,9 @@
       "unlinked": "Redirect pages to this page have been deleted.",
       "restricted": "Access to this page is restricted",
       "stale": "More than {{count}} year has passed since last update.",
-      "stale_plural": "More than {{count}} years has passed since last update."
+      "stale_plural": "More than {{count}} years has passed since last update.",
+      "expiration": "This share link will expire at <strong>{{expiredAt}}</strong>.",
+      "no_deadline":"This page has no expiration date"
     }
   },
   "page_edit": {
@@ -336,12 +362,16 @@
   },
   "toaster": {
     "update_successed": "Succeeded to update {{target}}",
+    "initialize_successed": "Succeeded to initialize {{target}}",
     "give_user_admin": "Succeeded to give {{username}} admin",
-    "remove_user_admin": "Succeeded to remove {{username}} admin ",
+    "remove_user_admin": "Succeeded to remove {{username}} admin",
     "activate_user_success": "Succeeded to activating {{username}}",
     "deactivate_user_success": "Succeeded to deactivate {{username}}",
-    "remove_user_success": "Succeeded to removing {{username}} ",
-    "remove_external_user_success": "Succeeded to remove {{accountId}} ",
+    "remove_user_success": "Succeeded to removing {{username}}",
+    "remove_external_user_success": "Succeeded to remove {{accountId}}",
+    "remove_share_link_success": "Succeeded to remove {{shareLinkId}}",
+    "issue_share_link": "Succeeded to issue new share link",
+    "remove_share_link": "Succeeded to remove {{count}} share links",
     "failed_to_reset_password":"Failed to reset password"
   },
   "template": {

+ 3 - 0
resource/locales/ja_JP/admin/admin.json

@@ -35,6 +35,9 @@
     "host": "ホスト",
     "port": "ポート",
     "user": "ユーザー",
+    "initialize_mail_settings": "設定を初期化",
+    "initialize_mail_modal_header": "メール設定の初期化",
+    "confirm_to_initialize_mail_settings": "一度初期化した設定は戻せません。本当に初期化しますか?",
     "aws_settings": "AWS設定",
     "aws_access": "AWS にアクセスするための設定を行います。AWS の設定を完了させると、ファイルアップロード機能、プロフィール写真機能などが有効になります。",
     "no_smtp_setting": "また、SMTP の設定が無い場合、SES を利用したメール送信が行われます。FromメールアドレスのVerify、プロダクション利用設定をする必要があります。",

+ 35 - 4
resource/locales/ja_JP/translation.json

@@ -19,6 +19,7 @@
   "Tag": "タグ",
   "Tags": "タグ",
   "New": "作成",
+  "Close": "閉じる",
   "Shortcuts": "ショートカット",
   "eg": "例:",
   "add": "追加",
@@ -30,6 +31,7 @@
   "User": "ユーザー",
   "status": "ステータス",
   "account_id": "アカウントID",
+  "Initialize": "初期化",
   "Update": "更新",
   "Update Page": "ページを更新",
   "Warning": "注意",
@@ -47,12 +49,16 @@
   "History": "更新履歴",
   "Presentation Mode": "プレゼンテーション",
   "Not available for guest": "ゲストユーザーは利用できません",
+  "Create Archive Page": "アーカイブページの作成",
+  "File type": "ファイル形式",
+  "Include Attachment File": "添付ファイルも含める",
+  "Include Comment": "コメントも含める",
+  "Include Subordinated Page": "配下ページも含める",
   "username": "ユーザー名",
   "Created": "作成日",
   "Last updated": "最終更新",
   "Last_Login": "最終ログイン",
   "Share": "共有",
-  "Share Link": "共有用リンク",
   "Markdown Link": "Markdown形式のリンク",
   "Create/Edit Template": "テンプレートページの作成/編集",
   "Go to this version": "このバージョンを見る",
@@ -191,6 +197,25 @@
     "password_is_not_set": "パスワードが設定されていません"
   },
   "security_settings": "セキュリティ設定",
+  "share_links": {
+    "Shere this page link to public": "外部に共有するリンクを発行する",
+    "share_link_list": "共有リンクリスト",
+    "share_link_management": "共有リンク管理",
+    "No_share_links":"共有リンクが存在しません",
+    "Share Link": "共有用リンク",
+    "Page Path": "ページパス",
+    "share_link_notice":"共有リンクを全て削除します",
+    "delete_all_share_links":"全ての共有リンクを削除します",
+    "expire": "有効期限",
+    "Days": "日間",
+    "Custom": "カスタム",
+    "description": "概要",
+    "enter_desc": "概要を入力",
+    "Unlimited": "無期限",
+    "Issue": "発行",
+    "share_settings" :"共有設定",
+    "Invalid_Number_of_Date" : "有効期限の日数には整数を入力してください"
+  },
   "API Settings": "API設定",
   "API Token Settings": "API Token設定",
   "Current API Token": "現在のAPI Token",
@@ -209,8 +234,8 @@
     "Copy to clipboard": "クリップボードにコピー",
     "Page path": "ページ名",
     "Page URL": "ページURL",
-    "Parmanent link": "パーマリンク",
-    "Page path and parmanent link": "ページ名とパーマリンク",
+    "Permanent link": "パーマリンク",
+    "Page path and permanent link": "ページ名とパーマリンク",
     "Markdown link": "マークダウン形式のリンク"
   },
   "search_help": {
@@ -250,7 +275,9 @@
       "duplicated": "このページは <code>%s</code> から複製されました。",
       "unlinked": "このページへのリダイレクトは削除されました。",
       "restricted": "このページの閲覧は制限されています",
-      "stale": "このページは最終更新日から{{count}}年以上が経過しています。"
+      "stale": "このページは最終更新日から{{count}}年以上が経過しています。",
+      "expiration": "この共有パーマリンクの有効期限は <strong>{{expiredAt}}</strong> です。",
+      "no_deadline": "このページに有効期限は設定されていません。"
     }
   },
   "page_edit": {
@@ -337,12 +364,16 @@
   },
   "toaster": {
     "update_successed": "{{target}}を更新しました",
+    "initialize_successed": "{{target}}を初期化しました",
     "give_user_admin": "{{username}}を管理者に設定しました",
     "remove_user_admin": "{{username}}を管理者から外しました",
     "activate_user_success": "{{username}}を有効化しました",
     "deactivate_user_success": "{{username}}を無効化しました",
     "remove_user_success": "{{username}}を削除しました",
     "remove_external_user_success": "{{accountId}}を削除しました",
+    "remove_share_link_success": "{{shareLinkId}}を削除しました",
+    "issue_share_link": "共有リンクを作成しました",
+    "remove_share_link": "共有リンクを{{count}}件削除しました",
     "failed_to_reset_password":"パスワードのリセットに失敗しました"
   },
   "template": {

+ 4 - 1
resource/locales/zh_CN/admin/admin.json

@@ -35,6 +35,9 @@
 		"host": "服务器",
 		"port": "端口号",
 		"user": "用户名",
+    "initialize_mail_settings": "初始化邮件设置",
+    "initialize_mail_modal_header": "初始化邮件设置",
+    "confirm_to_initialize_mail_settings": "You can't restore to the current settings. Are you sure you want to initialize e-mail settings?",
 		"aws_settings": "AWS设置",
 		"aws_access": "这是用于AWS设置的。如果您完成了AWS设置,文件上传功能,个人资料图片功能等将被启用。",
 		"no_smtp_setting": "如果您没有SMTP设置,电子邮件将通过SES发送。您需要从电子邮件地址和生产设置进行验证。",
@@ -315,4 +318,4 @@
 			"transfer_pages": "转移到另一组"
 		}
 	}
-}
+}

+ 30 - 7
resource/locales/zh_CN/translation.json

@@ -19,7 +19,8 @@
 	"administrator": "管理员",
 	"Tag": "标签",
 	"Tags": "Tags",
-	"New": "新建",
+  "New": "新建",
+  "Close": "Close",
 	"Shortcuts": "快捷方式",
 	"eg": "e.g.",
 	"add": "添加",
@@ -31,7 +32,8 @@
 	"User": "用户",
 	"status": "状态",
 	"account_id": "用户Id",
-	"Update": "更新",
+	"Initialize": "初始化",
+  "Update": "更新",
 	"Update Page": "更新本页",
 	"Warning": "警告",
 	"Sign in": "登录",
@@ -47,13 +49,13 @@
 	"Timeline View": "时间线",
 	"History": "历史",
 	"Presentation Mode": "演示文稿",
-	"Not available for guest": "Not available for guest",
+  "Not available for guest": "Not available for guest",
 	"username": "用户名",
 	"Created": "创建",
 	"Last updated": "上次更新",
-	"Last_Login": "上次登录",
+  "Last_Login": "上次登录",
 	"Share": "分享",
-	"Share Link": "分享链接",
+  "Share Link": "分享链接",
 	"Markdown Link": "Markdown链接",
 	"Create/Edit Template": "创建/编辑 模板页面",
 	"Unportalize": "未启动",
@@ -247,7 +249,8 @@
 			"unlinked": "将网页重定向到此网页已被删除。",
 			"restricted": "访问此页受到限制",
 			"stale": "自上次更新以来,已超过{{count}年。",
-			"stale_plural": "自上次更新以来已过去{{count}年以上。"
+      "stale_plural": "自上次更新以来已过去{{count}年以上。",
+      "no_deadline": "This page has no expiration date"
 		}
 	},
 	"page_edit": {
@@ -333,6 +336,7 @@
 	},
 	"toaster": {
 		"update_successed": "Succeeded to update {{target}}",
+    "initialize_successed": "Succeeded to initialize {{target}}",
 		"give_user_admin": "Succeeded to give {{username}} admin",
 		"remove_user_admin": "Succeeded to remove {{username}} admin ",
 		"activate_user_success": "Succeeded to activating {{username}}",
@@ -407,7 +411,26 @@
 		"someone_editing": "Someone editing this page on HackMD",
 		"this_page_has_draft": "This page has a draft on HackMD"
 	},
-	"security_settings": "安全设置",
+  "security_settings": "安全设置",
+  "share_links": {
+    "Shere this page link to public": "Shere this page link to public",
+    "share_link_list": "Share link list",
+    "share_link_management": "Share Link Management",
+    "No_share_links":"No share links",
+    "Share Link": "Share Link",
+    "Page Path": "Page Path",
+    "share_link_notice":"remove all share links",
+    "delete_all_share_links":"Delete all share links",
+    "expire": "Expiration",
+    "Days": "Days",
+    "Custom": "Custom",
+    "description": "description",
+    "enter_desc": "Enter description",
+    "Unlimited": "unlimited",
+    "Issue": "Issue",
+    "share_settings" :"Share settings",
+    "Invalid_Number_of_Date" : "You entered invalid value"
+  },
 	"security_setting": {
 		"Security settings": "安全设置",
 		"Guest Users Access": "来宾用户访问",

+ 3 - 2
src/client/js/admin.jsx

@@ -25,6 +25,7 @@ import AdminNavigation from './components/Admin/Common/AdminNavigation';
 
 import NavigationContainer from './services/NavigationContainer';
 
+import AdminSocketIoContainer from './services/AdminSocketIoContainer';
 import AdminHomeContainer from './services/AdminHomeContainer';
 import AdminCustomizeContainer from './services/AdminCustomizeContainer';
 import AdminUserGroupDetailContainer from './services/AdminUserGroupDetailContainer';
@@ -50,11 +51,11 @@ const logger = loggerFactory('growi:admin');
 appContainer.initContents();
 
 const { i18n } = appContainer;
-const websocketContainer = appContainer.getContainer('WebsocketContainer');
 
 // create unstated container instance
 const navigationContainer = new NavigationContainer(appContainer);
 const adminAppContainer = new AdminAppContainer(appContainer);
+const adminSocketIoContainer = new AdminSocketIoContainer(appContainer);
 const adminHomeContainer = new AdminHomeContainer(appContainer);
 const adminCustomizeContainer = new AdminCustomizeContainer(appContainer);
 const adminUsersContainer = new AdminUsersContainer(appContainer);
@@ -64,9 +65,9 @@ const adminMarkDownContainer = new AdminMarkDownContainer(appContainer);
 const adminUserGroupDetailContainer = new AdminUserGroupDetailContainer(appContainer);
 const injectableContainers = [
   appContainer,
-  websocketContainer,
   navigationContainer,
   adminAppContainer,
+  adminSocketIoContainer,
   adminHomeContainer,
   adminCustomizeContainer,
   adminUsersContainer,

+ 5 - 3
src/client/js/app.jsx

@@ -19,6 +19,7 @@ import PageComments from './components/PageComments';
 import PageTimeline from './components/PageTimeline';
 import CommentEditorLazyRenderer from './components/PageComment/CommentEditorLazyRenderer';
 import PageManagement from './components/Page/PageManagement';
+import PageShareManagement from './components/Page/PageShareManagement';
 import TrashPageAlert from './components/Page/TrashPageAlert';
 import PageAttachment from './components/PageAttachment';
 import PageStatusAlert from './components/PageStatusAlert';
@@ -45,7 +46,7 @@ const logger = loggerFactory('growi:cli:app');
 appContainer.initContents();
 
 const { i18n } = appContainer;
-const websocketContainer = appContainer.getContainer('WebsocketContainer');
+const socketIoContainer = appContainer.getContainer('SocketIoContainer');
 
 // create unstated container instance
 const navigationContainer = new NavigationContainer(appContainer);
@@ -55,7 +56,7 @@ const editorContainer = new EditorContainer(appContainer, defaultEditorOptions,
 const tagContainer = new TagContainer(appContainer);
 const personalContainer = new PersonalContainer(appContainer);
 const injectableContainers = [
-  appContainer, websocketContainer, navigationContainer, pageContainer, commentContainer, editorContainer, tagContainer, personalContainer,
+  appContainer, socketIoContainer, navigationContainer, pageContainer, commentContainer, editorContainer, tagContainer, personalContainer,
 ];
 
 logger.info('unstated containers have been initialized');
@@ -87,6 +88,7 @@ if (pageContainer.state.pageId != null) {
     'page-comment-write': <CommentEditorLazyRenderer />,
     'page-attachment': <PageAttachment />,
     'page-management': <PageManagement />,
+    'page-share-management': <PageShareManagement />,
 
     'revision-toc': <TableOfContents />,
     'seen-user-list': <SeenUserList />,
@@ -139,7 +141,7 @@ $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', () => {
   ReactDOM.render(
     <I18nextProvider i18n={i18n}>
       <ErrorBoundary>
-        <PageHistory pageId={pageContainer.state.pageId} crowi={appContainer} />
+        <PageHistory shareLinkId={pageContainer.state.shareLinkId} pageId={pageContainer.state.pageId} crowi={appContainer} />
       </ErrorBoundary>
     </I18nextProvider>, document.getElementById('revision-history'),
   );

+ 5 - 3
src/client/js/base.jsx

@@ -6,11 +6,12 @@ import Xss from '@commons/service/xss';
 import GrowiNavbar from './components/Navbar/GrowiNavbar';
 import GrowiNavbarBottom from './components/Navbar/GrowiNavbarBottom';
 import Sidebar from './components/Sidebar';
+import ShareLinkAlert from './components/Page/ShareLinkAlert';
 import HotkeysManager from './components/Hotkeys/HotkeysManager';
 import Fab from './components/Fab';
 
 import AppContainer from './services/AppContainer';
-import WebsocketContainer from './services/WebsocketContainer';
+import SocketIoContainer from './services/SocketIoContainer';
 import PageCreateModal from './components/PageCreateModal';
 
 const logger = loggerFactory('growi:cli:app');
@@ -26,7 +27,7 @@ window.xss = xss;
 // create unstated container instance
 const appContainer = new AppContainer();
 // eslint-disable-next-line no-unused-vars
-const websocketContainer = new WebsocketContainer(appContainer);
+const socketIoContainer = new SocketIoContainer(appContainer);
 
 appContainer.initApp();
 
@@ -45,9 +46,10 @@ const componentMappings = {
 
   'grw-sidebar-wrapper': <Sidebar />,
 
+  'share-link-alert': <ShareLinkAlert />,
+  'grw-fab-container': <Fab />,
   'grw-hotkeys-manager': <HotkeysManager />,
 
-  'grw-fab-container': <Fab />,
 };
 
 export { appContainer, componentMappings };

+ 65 - 2
src/client/js/components/Admin/App/MailSetting.jsx

@@ -3,12 +3,12 @@ import PropTypes from 'prop-types';
 import { withTranslation } from 'react-i18next';
 import loggerFactory from '@alias/logger';
 
+import { Modal, ModalHeader, ModalBody } from 'reactstrap';
 import { withUnstatedContainers } from '../../UnstatedUtils';
 import { toastSuccess, toastError } from '../../../util/apiNotification';
 
 import AppContainer from '../../../services/AppContainer';
 import AdminAppContainer from '../../../services/AdminAppContainer';
-import AdminUpdateButtonRow from '../Common/AdminUpdateButtonRow';
 
 const logger = loggerFactory('growi:appSettings');
 
@@ -17,7 +17,22 @@ class MailSetting extends React.Component {
   constructor(props) {
     super(props);
 
+    this.state = {
+      isInitializeValueModalOpen: false,
+    };
+
+    this.openInitializeValueModal = this.openInitializeValueModal.bind(this);
+    this.closeInitializeValueModal = this.closeInitializeValueModal.bind(this);
     this.submitHandler = this.submitHandler.bind(this);
+    this.initialize = this.initialize.bind(this);
+  }
+
+  openInitializeValueModal() {
+    this.setState({ isInitializeValueModalOpen: true });
+  }
+
+  closeInitializeValueModal() {
+    this.setState({ isInitializeValueModalOpen: false });
   }
 
   async submitHandler() {
@@ -33,6 +48,20 @@ class MailSetting extends React.Component {
     }
   }
 
+  async initialize() {
+    const { t, adminAppContainer } = this.props;
+
+    try {
+      await adminAppContainer.initializeMailSettingHandler();
+      toastSuccess(t('toaster.initialize_successed', { target: t('admin:app_setting.mail_settings') }));
+      this.closeInitializeValueModal();
+    }
+    catch (err) {
+      toastError(err);
+      logger.error(err);
+    }
+  }
+
   render() {
     const { t, adminAppContainer } = this.props;
 
@@ -94,7 +123,41 @@ class MailSetting extends React.Component {
           </div>
         </div>
 
-        <AdminUpdateButtonRow onClick={this.submitHandler} disabled={adminAppContainer.state.retrieveError != null} />
+        <div className="row my-3">
+          <div className="offset-5">
+            <button type="button" className="btn btn-primary" onClick={this.submitHandler} disabled={adminAppContainer.state.retrieveError != null}>
+              { t('Update') }
+            </button>
+          </div>
+          <div className="offset-1">
+            <button
+              type="button"
+              className="btn btn-secondary"
+              onClick={this.openInitializeValueModal}
+              disabled={adminAppContainer.state.retrieveError != null}
+            >
+              {t('admin:app_setting.initialize_mail_settings')}
+            </button>
+          </div>
+        </div>
+        <Modal isOpen={this.state.isInitializeValueModalOpen} toggle={this.closeInitializeValueModal} className="initialize-mail-settings">
+          <ModalHeader tag="h4" toggle={this.closeInitializeValueModal} className="bg-danger text-light">
+            {t('admin:app_setting.initialize_mail_modal_header')}
+          </ModalHeader>
+          <ModalBody>
+            <div className="text-center mb-4">
+              {t('admin:app_setting.confirm_to_initialize_mail_settings')}
+            </div>
+            <div className="text-center my-2">
+              <button type="button" className="btn btn-outline-secondary mr-4" onClick={this.closeInitializeValueModal}>
+                {t('Cancel')}
+              </button>
+              <button type="button" className="btn btn-danger" onClick={this.initialize}>
+                {t('Initialize')}
+              </button>
+            </div>
+          </ModalBody>
+        </Modal>
       </React.Fragment>
     );
   }

+ 7 - 7
src/client/js/components/Admin/ElasticsearchManagement/ElasticsearchManagement.jsx

@@ -4,7 +4,7 @@ import { withTranslation } from 'react-i18next';
 
 import { withUnstatedContainers } from '../../UnstatedUtils';
 import AppContainer from '../../../services/AppContainer';
-import WebsocketContainer from '../../../services/WebsocketContainer';
+import AdminSocketIoContainer from '../../../services/AdminSocketIoContainer';
 import { toastSuccess, toastError } from '../../../util/apiNotification';
 
 import StatusTable from './StatusTable';
@@ -45,22 +45,22 @@ class ElasticsearchManagement extends React.Component {
   }
 
   initWebSockets() {
-    const socket = this.props.websocketContainer.getWebSocket();
+    const socket = this.props.adminSocketIoContainer.getSocket();
 
-    socket.on('admin:addPageProgress', (data) => {
+    socket.on('addPageProgress', (data) => {
       this.setState({
         isRebuildingProcessing: true,
       });
     });
 
-    socket.on('admin:finishAddPage', (data) => {
+    socket.on('finishAddPage', (data) => {
       this.setState({
         isRebuildingProcessing: false,
         isRebuildingCompleted: true,
       });
     });
 
-    socket.on('admin:rebuildingFailed', (data) => {
+    socket.on('rebuildingFailed', (data) => {
       toastError(new Error(data.error), 'Rebuilding Index has failed.');
     });
   }
@@ -224,12 +224,12 @@ class ElasticsearchManagement extends React.Component {
 /**
  * Wrapper component for using unstated
  */
-const ElasticsearchManagementWrapper = withUnstatedContainers(ElasticsearchManagement, [AppContainer, WebsocketContainer]);
+const ElasticsearchManagementWrapper = withUnstatedContainers(ElasticsearchManagement, [AppContainer, AdminSocketIoContainer]);
 
 ElasticsearchManagement.propTypes = {
   t: PropTypes.func.isRequired, // i18next
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  websocketContainer: PropTypes.instanceOf(WebsocketContainer).isRequired,
+  adminSocketIoContainer: PropTypes.instanceOf(AdminSocketIoContainer).isRequired,
 };
 
 export default withTranslation()(ElasticsearchManagementWrapper);

+ 12 - 8
src/client/js/components/Admin/ElasticsearchManagement/RebuildIndexControls.jsx

@@ -4,7 +4,7 @@ import { withTranslation } from 'react-i18next';
 
 import { withUnstatedContainers } from '../../UnstatedUtils';
 import AppContainer from '../../../services/AppContainer';
-import WebsocketContainer from '../../../services/WebsocketContainer';
+import AdminSocketIoContainer from '../../../services/AdminSocketIoContainer';
 
 import ProgressBar from '../Common/ProgressBar';
 
@@ -25,17 +25,21 @@ class RebuildIndexControls extends React.Component {
   }
 
   initWebSockets() {
-    const socket = this.props.websocketContainer.getWebSocket();
+    const socket = this.props.adminSocketIoContainer.getSocket();
 
-    socket.on('admin:addPageProgress', (data) => {
+    socket.on('addPageProgress', (data) => {
       this.setState({
-        ...data,
+        total: data.totalCount,
+        current: data.count,
+        skip: data.skipped,
       });
     });
 
-    socket.on('admin:finishAddPage', (data) => {
+    socket.on('finishAddPage', (data) => {
       this.setState({
-        ...data,
+        total: data.totalCount,
+        current: data.count,
+        skip: data.skipped,
       });
     });
 
@@ -97,12 +101,12 @@ class RebuildIndexControls extends React.Component {
 /**
  * Wrapper component for using unstated
  */
-const RebuildIndexControlsWrapper = withUnstatedContainers(RebuildIndexControls, [AppContainer, WebsocketContainer]);
+const RebuildIndexControlsWrapper = withUnstatedContainers(RebuildIndexControls, [AppContainer, AdminSocketIoContainer]);
 
 RebuildIndexControls.propTypes = {
   t: PropTypes.func.isRequired, // i18next
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  websocketContainer: PropTypes.instanceOf(WebsocketContainer).isRequired,
+  adminSocketIoContainer: PropTypes.instanceOf(AdminSocketIoContainer).isRequired,
 
   isRebuildingProcessing: PropTypes.bool.isRequired,
   isRebuildingCompleted: PropTypes.bool.isRequired,

+ 4 - 4
src/client/js/components/Admin/ExportArchiveDataPage.jsx

@@ -8,7 +8,7 @@ import { withUnstatedContainers } from '../UnstatedUtils';
 // import { toastSuccess, toastError } from '../../../util/apiNotification';
 
 import AppContainer from '../../services/AppContainer';
-import WebsocketContainer from '../../services/WebsocketContainer';
+import AdminSocketIoContainer from '../../services/AdminSocketIoContainer';
 
 import ProgressBar from './Common/ProgressBar';
 
@@ -67,7 +67,7 @@ class ExportArchiveDataPage extends React.Component {
   }
 
   setupWebsocketEventHandler() {
-    const socket = this.props.websocketContainer.getWebSocket();
+    const socket = this.props.adminSocketIoContainer.getSocket();
 
     // websocket event
     socket.on('admin:onProgressForExport', ({ currentCount, totalCount, progressList }) => {
@@ -248,12 +248,12 @@ class ExportArchiveDataPage extends React.Component {
 ExportArchiveDataPage.propTypes = {
   t: PropTypes.func.isRequired, // i18next
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  websocketContainer: PropTypes.instanceOf(WebsocketContainer).isRequired,
+  adminSocketIoContainer: PropTypes.instanceOf(AdminSocketIoContainer).isRequired,
 };
 
 /**
  * Wrapper component for using unstated
  */
-const ExportArchiveDataPageWrapper = withUnstatedContainers(ExportArchiveDataPage, [AppContainer, WebsocketContainer]);
+const ExportArchiveDataPageWrapper = withUnstatedContainers(ExportArchiveDataPage, [AppContainer, AdminSocketIoContainer]);
 
 export default withTranslation()(ExportArchiveDataPageWrapper);

+ 5 - 5
src/client/js/components/Admin/ImportData/GrowiArchive/ImportForm.jsx

@@ -8,7 +8,7 @@ import ImportOptionForRevisions from '@commons/models/admin/import-option-for-re
 
 import { withUnstatedContainers } from '../../../UnstatedUtils';
 import AppContainer from '../../../../services/AppContainer';
-import WebsocketContainer from '../../../../services/WebsocketContainer';
+import AdminSocketIoContainer from '../../../../services/AdminSocketIoContainer';
 import { toastSuccess, toastError } from '../../../../util/apiNotification';
 
 
@@ -102,7 +102,7 @@ class ImportForm extends React.Component {
   }
 
   setupWebsocketEventHandler() {
-    const socket = this.props.websocketContainer.getWebSocket();
+    const socket = this.props.adminSocketIoContainer.getSocket();
 
     // websocket event
     // eslint-disable-next-line object-curly-newline
@@ -142,7 +142,7 @@ class ImportForm extends React.Component {
   }
 
   teardownWebsocketEventHandler() {
-    const socket = this.props.websocketContainer.getWebSocket();
+    const socket = this.props.adminSocketIoContainer.getSocket();
 
     socket.removeAllListeners('admin:onProgressForImport');
     socket.removeAllListeners('admin:onTerminateForImport');
@@ -493,7 +493,7 @@ class ImportForm extends React.Component {
 ImportForm.propTypes = {
   t: PropTypes.func.isRequired, // i18next
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  websocketContainer: PropTypes.instanceOf(WebsocketContainer).isRequired,
+  adminSocketIoContainer: PropTypes.instanceOf(AdminSocketIoContainer).isRequired,
 
   fileName: PropTypes.string,
   innerFileStats: PropTypes.arrayOf(PropTypes.object).isRequired,
@@ -504,6 +504,6 @@ ImportForm.propTypes = {
 /**
  * Wrapper component for using unstated
  */
-const ImportFormWrapper = withUnstatedContainers(ImportForm, [AppContainer, WebsocketContainer]);
+const ImportFormWrapper = withUnstatedContainers(ImportForm, [AppContainer, AdminSocketIoContainer]);
 
 export default withTranslation()(ImportFormWrapper);

+ 66 - 0
src/client/js/components/Admin/Security/DeleteAllShareLinksModal.jsx

@@ -0,0 +1,66 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+
+import { withTranslation } from 'react-i18next';
+
+import {
+  Button, Modal, ModalHeader, ModalBody, ModalFooter,
+} from 'reactstrap';
+
+const DeleteAllShareLinksModal = React.memo((props) => {
+  const { t } = props;
+
+  function closeModal() {
+    if (props.onClose == null) {
+      return;
+    }
+
+    props.onClose();
+  }
+
+  function deleteAllLinkHandler() {
+    if (props.onClickDeleteButton == null) {
+      return;
+    }
+
+    props.onClickDeleteButton();
+
+    closeModal();
+  }
+
+  function closeButtonHandler() {
+    closeModal();
+  }
+
+  return (
+    <Modal isOpen={props.isOpen} toggle={closeButtonHandler} className="page-comment-delete-modal">
+      <ModalHeader tag="h4" toggle={closeButtonHandler} className="bg-danger text-light">
+        <span>
+          <i className="icon-fw icon-fire"></i>
+          {t('share_links.delete_all_share_links')}
+        </span>
+      </ModalHeader>
+      <ModalBody>
+        { t('share_links.share_link_notice')}
+      </ModalBody>
+      <ModalFooter>
+        <Button onClick={closeButtonHandler}>{t('Cancel')}</Button>
+        <Button color="danger" onClick={deleteAllLinkHandler}>
+          <i className="icon icon-fire"></i>
+          {t('Delete')}
+        </Button>
+      </ModalFooter>
+    </Modal>
+  );
+
+});
+
+DeleteAllShareLinksModal.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+
+  isOpen: PropTypes.bool.isRequired,
+  onClose: PropTypes.func,
+  onClickDeleteButton: PropTypes.func,
+};
+
+export default withTranslation()(DeleteAllShareLinksModal);

+ 8 - 1
src/client/js/components/Admin/Security/SecurityManagement.jsx

@@ -18,6 +18,7 @@ import GoogleSecuritySetting from './GoogleSecuritySetting';
 import GitHubSecuritySetting from './GitHubSecuritySetting';
 import TwitterSecuritySetting from './TwitterSecuritySetting';
 import FacebookSecuritySetting from './FacebookSecuritySetting';
+import ShareLinkSetting from './ShareLinkSetting';
 
 class SecurityManagement extends React.Component {
 
@@ -44,10 +45,16 @@ class SecurityManagement extends React.Component {
     const { activeTab, activeComponents } = this.state;
     return (
       <Fragment>
-        <div>
+        <div className="mb-5">
           <SecuritySetting />
         </div>
 
+        {/* Shared Link List */}
+        <div className="mb-5">
+          <ShareLinkSetting />
+        </div>
+
+
         {/* XSS configuration link */}
         <div className="mb-5">
           <h2 className="border-bottom">{t('security_setting.xss_prevent_setting')}</h2>

+ 147 - 0
src/client/js/components/Admin/Security/ShareLinkSetting.jsx

@@ -0,0 +1,147 @@
+import React, { Fragment } from 'react';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
+
+import { withUnstatedContainers } from '../../UnstatedUtils';
+import { toastSuccess, toastError } from '../../../util/apiNotification';
+
+import PaginationWrapper from '../../PaginationWrapper';
+
+import AppContainer from '../../../services/AppContainer';
+import AdminGeneralSecurityContainer from '../../../services/AdminGeneralSecurityContainer';
+
+import DeleteAllShareLinksModal from './DeleteAllShareLinksModal';
+import ShareLinkList from '../../ShareLinkList';
+
+class ShareLinkSetting extends React.Component {
+
+  constructor() {
+    super();
+
+    this.state = {
+      isDeleteConfirmModalShown: false,
+    };
+    this.getShareLinkList = this.getShareLinkList.bind(this);
+    this.showDeleteConfirmModal = this.showDeleteConfirmModal.bind(this);
+    this.closeDeleteConfirmModal = this.closeDeleteConfirmModal.bind(this);
+    this.deleteAllLinksButtonHandler = this.deleteAllLinksButtonHandler.bind(this);
+    this.deleteLinkById = this.deleteLinkById.bind(this);
+  }
+
+  componentWillMount() {
+    this.getShareLinkList(1);
+  }
+
+  async getShareLinkList(page) {
+    try {
+      await this.props.adminGeneralSecurityContainer.retrieveShareLinksByPagingNum(page);
+    }
+    catch (err) {
+      toastError(err);
+    }
+
+  }
+
+  showDeleteConfirmModal() {
+    this.setState({ isDeleteConfirmModalShown: true });
+  }
+
+  closeDeleteConfirmModal() {
+    this.setState({ isDeleteConfirmModalShown: false });
+  }
+
+  async deleteAllLinksButtonHandler() {
+    const { t, appContainer } = this.props;
+
+    try {
+      const res = await appContainer.apiv3Delete('/share-links/all');
+      const { deletedCount } = res.data;
+      toastSuccess(t('toaster.remove_share_link', { count: deletedCount }));
+    }
+    catch (err) {
+      toastError(err);
+    }
+    this.getShareLinkList(1);
+  }
+
+  async deleteLinkById(shareLinkId) {
+    const { t, appContainer, adminGeneralSecurityContainer } = this.props;
+
+    try {
+      const res = await appContainer.apiv3Delete(`/share-links/${shareLinkId}`);
+      const { deletedShareLink } = res.data;
+      toastSuccess(t('toaster.remove_share_link_success', { shareLinkId: deletedShareLink._id }));
+    }
+    catch (err) {
+      toastError(err);
+    }
+
+    this.getShareLinkList(adminGeneralSecurityContainer.state.shareLinksActivePage);
+  }
+
+
+  render() {
+    const { t, adminGeneralSecurityContainer } = this.props;
+
+    const pager = (
+      <div className="pull-right my-3">
+        <PaginationWrapper
+          activePage={adminGeneralSecurityContainer.state.shareLinksActivePage}
+          changePage={this.getShareLinkList}
+          totalItemsCount={adminGeneralSecurityContainer.state.totalshareLinks}
+          pagingLimit={adminGeneralSecurityContainer.state.shareLinksPagingLimit}
+        />
+      </div>
+    );
+
+    const deleteAllButton = (
+      adminGeneralSecurityContainer.state.shareLinks.length > 0
+        ? (
+          <button
+            className="pull-right btn btn-danger"
+            type="button"
+            onClick={this.showDeleteConfirmModal}
+          >
+            {t('share_links.delete_all_share_links')}
+          </button>
+        )
+        : (
+          <p className="pull-right mr-2">{t('share_links.No_share_links')}</p>
+        )
+    );
+
+    return (
+      <Fragment>
+        <div className="mb-3">
+          {deleteAllButton}
+          <h2 className="alert-anchor border-bottom">{t('share_links.share_link_management')}</h2>
+        </div>
+
+        {pager}
+        <ShareLinkList
+          shareLinks={adminGeneralSecurityContainer.state.shareLinks}
+          onClickDeleteButton={this.deleteLinkById}
+          isAdmin
+        />
+
+        <DeleteAllShareLinksModal
+          isOpen={this.state.isDeleteConfirmModalShown}
+          onClose={this.closeDeleteConfirmModal}
+          onClickDeleteButton={this.deleteAllLinksButtonHandler}
+        />
+
+      </Fragment>
+    );
+  }
+
+}
+
+const ShareLinkSettingWrapper = withUnstatedContainers(ShareLinkSetting, [AppContainer, AdminGeneralSecurityContainer]);
+
+ShareLinkSetting.propTypes = {
+  t: PropTypes.func.isRequired, //  i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  adminGeneralSecurityContainer: PropTypes.instanceOf(AdminGeneralSecurityContainer).isRequired,
+};
+
+export default withTranslation()(ShareLinkSettingWrapper);

+ 139 - 0
src/client/js/components/OutsideShareLinkModal.jsx

@@ -0,0 +1,139 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+
+import {
+  Modal, ModalHeader, ModalBody,
+} from 'reactstrap';
+
+import { withTranslation } from 'react-i18next';
+
+import { withUnstatedContainers } from './UnstatedUtils';
+
+import AppContainer from '../services/AppContainer';
+import PageContainer from '../services/PageContainer';
+
+import ShareLinkList from './ShareLinkList';
+import ShareLinkForm from './ShareLinkForm';
+
+import { toastSuccess, toastError } from '../util/apiNotification';
+
+class OutsideShareLinkModal extends React.Component {
+
+  constructor() {
+    super();
+    this.state = {
+      shareLinks: [],
+      isOpenShareLinkForm: false,
+    };
+
+    this.toggleShareLinkFormHandler = this.toggleShareLinkFormHandler.bind(this);
+    this.deleteAllLinksButtonHandler = this.deleteAllLinksButtonHandler.bind(this);
+    this.deleteLinkById = this.deleteLinkById.bind(this);
+  }
+
+  componentDidMount() {
+    this.retrieveShareLinks();
+  }
+
+  async retrieveShareLinks() {
+    const { appContainer, pageContainer } = this.props;
+    const { pageId } = pageContainer.state;
+
+    try {
+      const res = await appContainer.apiv3.get('/share-links/', { relatedPage: pageId });
+      const { shareLinksResult } = res.data;
+      this.setState({ shareLinks: shareLinksResult });
+    }
+    catch (err) {
+      toastError(err);
+    }
+
+  }
+
+  toggleShareLinkFormHandler() {
+    this.setState({ isOpenShareLinkForm: !this.state.isOpenShareLinkForm });
+    this.retrieveShareLinks();
+  }
+
+  async deleteAllLinksButtonHandler() {
+    const { t, appContainer, pageContainer } = this.props;
+    const { pageId } = pageContainer.state;
+
+    try {
+      const res = await appContainer.apiv3.delete('/share-links/', { relatedPage: pageId });
+      const count = res.data.n;
+      toastSuccess(t('toaster.remove_share_link', { count }));
+    }
+    catch (err) {
+      toastError(err);
+    }
+
+    this.retrieveShareLinks();
+  }
+
+  async deleteLinkById(shareLinkId) {
+    const { t, appContainer } = this.props;
+
+    try {
+      const res = await appContainer.apiv3Delete(`/share-links/${shareLinkId}`);
+      const { deletedShareLink } = res.data;
+      toastSuccess(t('toaster.remove_share_link_success', { shareLinkId: deletedShareLink._id }));
+    }
+    catch (err) {
+      toastError(err);
+    }
+
+    this.retrieveShareLinks();
+  }
+
+  render() {
+    const { t } = this.props;
+
+    return (
+      <Modal size="xl" isOpen={this.props.isOpen} toggle={this.props.onClose}>
+        <ModalHeader tag="h4" toggle={this.props.onClose} className="bg-primary text-light">{t('share_links.Shere this page link to public')}
+        </ModalHeader>
+        <ModalBody>
+          <div className="container">
+            <h3 className="grw-modal-head  d-flex  pb-2">
+              { t('share_links.share_link_list') }
+              <button className="btn btn-danger ml-auto " type="button" onClick={this.deleteAllLinksButtonHandler}>{t('delete_all')}</button>
+            </h3>
+
+            <div>
+              <ShareLinkList
+                shareLinks={this.state.shareLinks}
+                onClickDeleteButton={this.deleteLinkById}
+              />
+              <button
+                className="btn btn-outline-secondary d-block mx-auto px-5 mb-3"
+                type="button"
+                onClick={this.toggleShareLinkFormHandler}
+              >
+                {this.state.isOpenShareLinkForm ? t('Close') : t('New')}
+              </button>
+              {this.state.isOpenShareLinkForm && <ShareLinkForm onCloseForm={this.toggleShareLinkFormHandler} />}
+            </div>
+          </div>
+        </ModalBody>
+      </Modal>
+    );
+  }
+
+}
+
+/**
+ * Wrapper component for using unstated
+ */
+const ModalControlWrapper = withUnstatedContainers(OutsideShareLinkModal, [AppContainer, PageContainer]);
+
+OutsideShareLinkModal.propTypes = {
+  t: PropTypes.func.isRequired, //  i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
+
+  isOpen: PropTypes.bool.isRequired,
+  onClose: PropTypes.func.isRequired,
+};
+
+export default withTranslation()(ModalControlWrapper);

+ 4 - 1
src/client/js/components/Page.jsx

@@ -9,6 +9,7 @@ import EditorContainer from '../services/EditorContainer';
 
 import MarkdownTable from '../models/MarkdownTable';
 
+import LinkEditModal from './PageEditor/LinkEditModal';
 import RevisionRenderer from './Page/RevisionRenderer';
 import HandsontableModal from './PageEditor/HandsontableModal';
 import DrawioModal from './PageEditor/DrawioModal';
@@ -29,6 +30,7 @@ class Page extends React.Component {
 
     this.growiRenderer = this.props.appContainer.getRenderer('page');
 
+    this.linkEditModal = React.createRef();
     this.handsontableModal = React.createRef();
     this.drawioModal = React.createRef();
 
@@ -59,7 +61,7 @@ class Page extends React.Component {
    */
   launchDrawioModal(beginLineNumber, endLineNumber) {
     const markdown = this.props.pageContainer.state.markdown;
-    const drawioMarkdownArray = markdown.split(/\r\n|\r|\n/).slice(beginLineNumber, endLineNumber);
+    const drawioMarkdownArray = markdown.split(/\r\n|\r|\n/).slice(beginLineNumber - 1, endLineNumber);
     const drawioData = drawioMarkdownArray.slice(1, drawioMarkdownArray.length - 1).join('\n').trim();
     this.setState({ currentTargetDrawioArea: { beginLineNumber, endLineNumber } });
     this.drawioModal.current.show(drawioData);
@@ -137,6 +139,7 @@ class Page extends React.Component {
 
         { isLoggedIn && (
           <>
+            <LinkEditModal ref={this.LinkEditModal} />
             <HandsontableModal ref={this.handsontableModal} onSave={this.saveHandlerForHandsontableModal} />
             <DrawioModal ref={this.drawioModal} onSave={this.saveHandlerForDrawioModal} />
           </>

+ 29 - 16
src/client/js/components/Page/CopyDropdown.jsx

@@ -21,6 +21,8 @@ class CopyDropdown extends React.Component {
       isParamsAppended: true,
     };
 
+    this.id = (Math.random() * 1000).toString();
+
     this.toggle = this.toggle.bind(this);
     this.showToolTip = this.showToolTip.bind(this);
     this.generatePagePathWithParams = this.generatePagePathWithParams.bind(this);
@@ -64,11 +66,14 @@ class CopyDropdown extends React.Component {
   }
 
   generatePermalink() {
-    const { pageId } = this.props;
+    const { pageId, isShareLinkMode } = this.props;
 
     if (pageId == null) {
       return null;
     }
+    if (isShareLinkMode) {
+      return decodeURI(`${origin}/share/${pageId}`);
+    }
 
     return decodeURI(`${origin}/${pageId}${this.uriParams}`);
   }
@@ -90,28 +95,36 @@ class CopyDropdown extends React.Component {
   );
 
   render() {
-    const { t, pageId } = this.props;
+    const {
+      t, pageId, isShareLinkMode,
+    } = this.props;
     const { isParamsAppended } = this.state;
 
     const pagePathWithParams = this.generatePagePathWithParams();
     const pagePathUrl = this.generatePagePathUrl();
     const permalink = this.generatePermalink();
 
-    const { DropdownItemContents } = this;
+    const copyTarget = isShareLinkMode ? `copyShareLink${pageId}` : 'copyPagePathDropdown';
+    const dropdownToggleStyle = isShareLinkMode ? 'btn btn-secondary' : 'd-block text-muted bg-transparent btn-copy border-0';
+
+    const { id, DropdownItemContents } = this;
+
+    const customSwitchForParamsId = `customSwitchForParams_${id}`;
 
     return (
       <>
-        <UncontrolledDropdown id="copyPagePathDropdown" className="grw-copy-dropdown">
-
+        <UncontrolledDropdown id={copyTarget} className="grw-copy-dropdown">
           <DropdownToggle
             caret
-            className="d-block text-muted bg-transparent btn-copy border-0"
+            className={dropdownToggleStyle}
             style={this.props.buttonStyle}
           >
-            <i className="ti-clipboard"></i>
+            { isShareLinkMode ? (
+              <>Copy Link</>
+            ) : (<i className="ti-clipboard"></i>)}
           </DropdownToggle>
 
-          <DropdownMenu>
+          <DropdownMenu positionFixed modifiers={{ preventOverflow: { boundariesElement: null } }}>
 
             <div className="d-flex align-items-center justify-content-between">
               <DropdownItem header className="px-3">
@@ -120,12 +133,12 @@ class CopyDropdown extends React.Component {
               <div className="px-3 custom-control custom-switch custom-switch-sm">
                 <input
                   type="checkbox"
-                  id="customSwitchForParams"
+                  id={customSwitchForParamsId}
                   className="custom-control-input"
                   checked={isParamsAppended}
                   onChange={e => this.setState({ isParamsAppended: !isParamsAppended })}
                 />
-                <label className="custom-control-label small" htmlFor="customSwitchForParams">Append params</label>
+                <label className="custom-control-label small" htmlFor={customSwitchForParamsId}>Append params</label>
               </div>
             </div>
 
@@ -146,25 +159,24 @@ class CopyDropdown extends React.Component {
                 <DropdownItemContents title={t('copy_to_clipboard.Page URL')} contents={pagePathUrl} />
               </DropdownItem>
             </CopyToClipboard>
-
             <DropdownItem divider className="my-0"></DropdownItem>
 
-            {/* Parmanent Link */}
+            {/* Permanent Link */}
             { pageId && (
               <CopyToClipboard text={permalink} onCopy={this.showToolTip}>
                 <DropdownItem className="px-3">
-                  <DropdownItemContents title={t('copy_to_clipboard.Parmanent link')} contents={permalink} />
+                  <DropdownItemContents title={t('copy_to_clipboard.Permanent link')} contents={permalink} />
                 </DropdownItem>
               </CopyToClipboard>
             )}
 
             <DropdownItem divider className="my-0"></DropdownItem>
 
-            {/* Page path + Parmanent Link */}
+            {/* Page path + Permanent Link */}
             { pageId && (
               <CopyToClipboard text={`${pagePathWithParams}\n${permalink}`} onCopy={this.showToolTip}>
                 <DropdownItem className="px-3">
-                  <DropdownItemContents title={t('copy_to_clipboard.Page path and parmanent link')} contents={<>{pagePathWithParams}<br />{permalink}</>} />
+                  <DropdownItemContents title={t('copy_to_clipboard.Page path and permanent link')} contents={<>{pagePathWithParams}<br />{permalink}</>} />
                 </DropdownItem>
               </CopyToClipboard>
             )}
@@ -183,7 +195,7 @@ class CopyDropdown extends React.Component {
 
         </UncontrolledDropdown>
 
-        <Tooltip placement="bottom" isOpen={this.state.tooltipOpen} target="copyPagePathDropdown" fade={false}>
+        <Tooltip placement="bottom" isOpen={this.state.tooltipOpen} target={copyTarget} fade={false}>
           copied!
         </Tooltip>
       </>
@@ -198,6 +210,7 @@ CopyDropdown.propTypes = {
   pagePath: PropTypes.string.isRequired,
   pageId: PropTypes.string,
   buttonStyle: PropTypes.object,
+  isShareLinkMode: PropTypes.bool,
 };
 
 export default withTranslation()(CopyDropdown);

+ 38 - 11
src/client/js/components/Page/PageManagement.jsx

@@ -1,5 +1,6 @@
 import React, { useState } from 'react';
 import PropTypes from 'prop-types';
+import { UncontrolledTooltip } from 'reactstrap';
 import { withTranslation } from 'react-i18next';
 
 import { isTopPage } from '@commons/util/path-utils';
@@ -83,6 +84,10 @@ const PageManagement = (props) => {
   }
 
   function renderModals() {
+    if (currentUser == null) {
+      return null;
+    }
+
     return (
       <>
         <PageRenameModal
@@ -108,19 +113,41 @@ const PageManagement = (props) => {
     );
   }
 
+  function renderDotsIconForCurrentUser() {
+    return (
+      <>
+        <button
+          type="button"
+          className="btn-link nav-link bg-transparent dropdown-toggle dropdown-toggle-no-caret"
+          data-toggle="dropdown"
+        >
+          <i className="icon-options-vertical"></i>
+        </button>
+      </>
+    );
+  }
+
+  function renderDotsIconForGuestUser() {
+    return (
+      <>
+        <button
+          type="button"
+          className="btn nav-link bg-transparent dropdown-toggle dropdown-toggle-no-caret disabled"
+          id="icon-options-guest-tltips"
+        >
+          <i className="icon-options-vertical"></i>
+        </button>
+        <UncontrolledTooltip placement="top" target="icon-options-guest-tltips">
+          {t('Not available for guest')}
+        </UncontrolledTooltip>
+      </>
+    );
+  }
+
+
   return (
     <>
-      <a
-        role="button"
-        className={`nav-link dropdown-toggle dropdown-toggle-no-caret ${currentUser == null && 'dropdown-toggle-disabled'}`}
-        href="#"
-        data-toggle={`${currentUser == null ? 'tooltip' : 'dropdown'}`}
-        data-placement="top"
-        data-container="body"
-        title={t('Not available for guest')}
-      >
-        <i className="icon-options-vertical"></i>
-      </a>
+      {currentUser == null ? renderDotsIconForGuestUser() : renderDotsIconForCurrentUser()}
       <div className="dropdown-menu dropdown-menu-right">
         {!isTopPagePath && renderDropdownItemForNotTopPage()}
         <button className="dropdown-item" type="button" onClick={openPageTemplateModalHandler}>

+ 100 - 0
src/client/js/components/Page/PageShareManagement.jsx

@@ -0,0 +1,100 @@
+import React, { useState } from 'react';
+import PropTypes from 'prop-types';
+import { UncontrolledTooltip } from 'reactstrap';
+import { withTranslation } from 'react-i18next';
+import { withUnstatedContainers } from '../UnstatedUtils';
+import AppContainer from '../../services/AppContainer';
+import PageContainer from '../../services/PageContainer';
+import OutsideShareLinkModal from '../OutsideShareLinkModal';
+
+const PageShareManagement = (props) => {
+  const { t, appContainer, pageContainer } = props;
+
+  const { currentUser } = appContainer;
+
+  const [isOutsideShareLinkModalShown, setIsOutsideShareLinkModalShown] = useState(false);
+
+
+  function openOutsideShareLinkModalHandler() {
+    setIsOutsideShareLinkModalShown(true);
+  }
+
+  function closeOutsideShareLinkModalHandler() {
+    setIsOutsideShareLinkModalShown(false);
+  }
+
+  function renderModals() {
+    if (currentUser == null) {
+      return null;
+    }
+
+    return (
+      <>
+        <OutsideShareLinkModal
+          isOpen={isOutsideShareLinkModalShown}
+          onClose={closeOutsideShareLinkModalHandler}
+        />
+      </>
+    );
+  }
+
+
+  function renderCurrentUser() {
+    return (
+      <>
+        <button
+          type="button"
+          className="btn-link nav-link bg-transparent dropdown-toggle dropdown-toggle-no-caret"
+          data-toggle="dropdown"
+        >
+          <i className="icon-share"></i>
+        </button>
+      </>
+    );
+  }
+
+  function renderGuestUser() {
+    return (
+      <>
+        <button
+          type="button"
+          className="btn nav-link bg-transparent dropdown-toggle dropdown-toggle-no-caret disabled"
+          id="auth-guest-tltips"
+        >
+          <i className="icon-share"></i>
+        </button>
+        <UncontrolledTooltip placement="top" target="auth-guest-tltips">
+          {t('Not available for guest')}
+        </UncontrolledTooltip>
+      </>
+    );
+  }
+
+  return (
+    <>
+      {currentUser == null ? renderGuestUser() : renderCurrentUser()}
+      <div className="dropdown-menu dropdown-menu-right">
+        <button className="dropdown-item" type="button" onClick={openOutsideShareLinkModalHandler}>
+          <i className="icon-fw icon-link"></i>{t('share_links.Shere this page link to public')}
+          <span className="ml-2 badge badge-info badge-pill">{pageContainer.state.shareLinksNumber}</span>
+        </button>
+      </div>
+      {renderModals()}
+    </>
+  );
+
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const PageShareManagementWrapper = withUnstatedContainers(PageShareManagement, [AppContainer, PageContainer]);
+
+
+PageShareManagement.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
+};
+
+export default withTranslation()(PageShareManagementWrapper);

+ 59 - 0
src/client/js/components/Page/ShareLinkAlert.jsx

@@ -0,0 +1,59 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+
+import { withTranslation } from 'react-i18next';
+
+const ShareLinkAlert = (props) => {
+  const { t } = props;
+
+
+  const shareContent = document.getElementById('is-shared-page');
+  const expiredAt = shareContent.getAttribute('data-share-link-expired-at');
+  const createdAt = shareContent.getAttribute('data-share-link-created-at');
+
+  function generateRatio() {
+    const wholeTime = new Date(expiredAt).getTime() - new Date(createdAt).getTime();
+    const remainingTime = new Date(expiredAt).getTime() - new Date().getTime();
+    return remainingTime / wholeTime;
+  }
+
+  let ratio = 1;
+
+  if (expiredAt !== '') {
+    ratio = generateRatio();
+  }
+
+  function specifyColor() {
+    let color;
+    if (ratio >= 0.75) {
+      color = 'success';
+    }
+    else if (ratio < 0.75 && ratio >= 0.5) {
+      color = 'info';
+    }
+    else if (ratio < 0.5 && ratio >= 0.25) {
+      color = 'warning';
+    }
+    else {
+      color = 'danger';
+    }
+    return color;
+  }
+
+  return (
+    <p className={`alert alert-${specifyColor()} py-3 px-4`}>
+      <i className="icon-fw icon-link"></i>
+      {(expiredAt === '' ? <span>{t('page_page.notice.no_deadline')}</span>
+      // eslint-disable-next-line react/no-danger
+      : <span dangerouslySetInnerHTML={{ __html: t('page_page.notice.expiration', { expiredAt }) }} />
+      )}
+    </p>
+  );
+};
+
+
+ShareLinkAlert.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+};
+
+export default withTranslation()(ShareLinkAlert);

+ 0 - 1
src/client/js/components/PageCreateModal.jsx

@@ -162,7 +162,6 @@ const PageCreateModal = (props) => {
               {isReachable
                 ? (
                   <PagePathAutoComplete
-                    crowi={appContainer}
                     initializedPath={pathname}
                     addTrailingSlash
                     onSubmit={ppacSubmitHandler}

+ 0 - 1
src/client/js/components/PageDuplicateModal.jsx

@@ -80,7 +80,6 @@ const PageDuplicateModal = (props) => {
               {isReachable
               ? (
                 <PagePathAutoComplete
-                  crowi={appContainer}
                   initializedPath={path}
                   onSubmit={ppacSubmitHandler}
                   onInputChange={ppacInputChangeHandler}

+ 26 - 1
src/client/js/components/PageEditor/CodeMirrorEditor.jsx

@@ -16,8 +16,10 @@ import pasteHelper from './PasteHelper';
 import EmojiAutoCompleteHelper from './EmojiAutoCompleteHelper';
 import PreventMarkdownListInterceptor from './PreventMarkdownListInterceptor';
 import MarkdownTableInterceptor from './MarkdownTableInterceptor';
+import mlu from './MarkdownLinkUtil';
 import mtu from './MarkdownTableUtil';
 import mdu from './MarkdownDrawioUtil';
+import LinkEditModal from './LinkEditModal';
 import HandsontableModal from './HandsontableModal';
 import EditorIcon from './EditorIcon';
 import DrawioModal from './DrawioModal';
@@ -54,6 +56,7 @@ require('../../util/codemirror/autorefresh.ext');
 
 
 const MARKDOWN_TABLE_ACTIVATED_CLASS = 'markdown-table-activated';
+const MARKDOWN_LINK_ACTIVATED_CLASS = 'markdown-link-activated';
 
 export default class CodeMirrorEditor extends AbstractEditor {
 
@@ -71,6 +74,7 @@ export default class CodeMirrorEditor extends AbstractEditor {
       additionalClassSet: new Set(),
     };
 
+    this.linkEditModal = React.createRef();
     this.handsontableModal = React.createRef();
     this.drawioModal = React.createRef();
 
@@ -98,6 +102,7 @@ export default class CodeMirrorEditor extends AbstractEditor {
     this.renderCheatsheetModalButton = this.renderCheatsheetModalButton.bind(this);
 
     this.makeHeaderHandler = this.makeHeaderHandler.bind(this);
+    this.showLinkEditHandler = this.showLinkEditHandler.bind(this);
     this.showHandsonTableHandler = this.showHandsonTableHandler.bind(this);
     this.showDrawioHandler = this.showDrawioHandler.bind(this);
   }
@@ -462,8 +467,10 @@ export default class CodeMirrorEditor extends AbstractEditor {
   cursorHandler(editor, event) {
     const { additionalClassSet } = this.state;
     const hasCustomClass = additionalClassSet.has(MARKDOWN_TABLE_ACTIVATED_CLASS);
+    const hasLinkClass = additionalClassSet.has(MARKDOWN_LINK_ACTIVATED_CLASS);
 
     const isInTable = mtu.isInTable(editor);
+    const isInLink = mlu.isInLink(editor);
 
     if (!hasCustomClass && isInTable) {
       additionalClassSet.add(MARKDOWN_TABLE_ACTIVATED_CLASS);
@@ -474,6 +481,16 @@ export default class CodeMirrorEditor extends AbstractEditor {
       additionalClassSet.delete(MARKDOWN_TABLE_ACTIVATED_CLASS);
       this.setState({ additionalClassSet });
     }
+
+    if (!hasLinkClass && isInLink) {
+      additionalClassSet.add(MARKDOWN_LINK_ACTIVATED_CLASS);
+      this.setState({ additionalClassSet });
+    }
+
+    if (hasLinkClass && !isInLink) {
+      additionalClassSet.delete(MARKDOWN_LINK_ACTIVATED_CLASS);
+      this.setState({ additionalClassSet });
+    }
   }
 
   changeHandler(editor, data, value) {
@@ -649,6 +666,10 @@ export default class CodeMirrorEditor extends AbstractEditor {
     cm.focus();
   }
 
+  showLinkEditHandler() {
+    this.linkEditModal.current.show(mlu.getMarkdownLink(this.getCodeMirror()));
+  }
+
   showHandsonTableHandler() {
     this.handsontableModal.current.show(mtu.getMarkdownTable(this.getCodeMirror()));
   }
@@ -745,7 +766,7 @@ export default class CodeMirrorEditor extends AbstractEditor {
         color={null}
         size="sm"
         title="Link"
-        onClick={this.createReplaceSelectionHandler('[', ']()')}
+        onClick={this.showLinkEditHandler}
       >
         <EditorIcon icon="Link" />
       </Button>,
@@ -849,6 +870,10 @@ export default class CodeMirrorEditor extends AbstractEditor {
 
         { this.renderCheatsheetOverlay() }
 
+        <LinkEditModal
+          ref={this.linkEditModal}
+          onSave={(link) => { return mlu.replaceFocusedMarkdownLinkWithEditor(this.getCodeMirror(), link) }}
+        />
         <HandsontableModal
           ref={this.handsontableModal}
           onSave={(table) => { return mtu.replaceFocusedMarkdownTableWithEditor(this.getCodeMirror(), table) }}

+ 353 - 0
src/client/js/components/PageEditor/LinkEditModal.jsx

@@ -0,0 +1,353 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+
+import {
+  Modal,
+  ModalHeader,
+  ModalBody,
+  ModalFooter,
+} from 'reactstrap';
+
+import { debounce } from 'throttle-debounce';
+
+import path from 'path';
+import Preview from './Preview';
+
+import AppContainer from '../../services/AppContainer';
+import PageContainer from '../../services/PageContainer';
+
+import SearchTypeahead from '../SearchTypeahead';
+import Linker from '../../models/Linker';
+
+import { withUnstatedContainers } from '../UnstatedUtils';
+
+class LinkEditModal extends React.PureComponent {
+
+  constructor(props) {
+    super(props);
+
+    this.state = {
+      show: false,
+      isUseRelativePath: false,
+      isUsePermanentLink: false,
+      linkInputValue: '',
+      labelInputValue: '',
+      linkerType: Linker.types.markdownLink,
+      markdown: '',
+      permalink: '',
+    };
+
+    this.isApplyPukiwikiLikeLinkerPlugin = window.growiRenderer.preProcessors.some(process => process.constructor.name === 'PukiwikiLikeLinker');
+
+    this.show = this.show.bind(this);
+    this.hide = this.hide.bind(this);
+    this.cancel = this.cancel.bind(this);
+    this.handleChangeTypeahead = this.handleChangeTypeahead.bind(this);
+    this.handleChangeLabelInput = this.handleChangeLabelInput.bind(this);
+    this.handleChangeLinkInput = this.handleChangeLinkInput.bind(this);
+    this.handleSelecteLinkerType = this.handleSelecteLinkerType.bind(this);
+    this.toggleIsUseRelativePath = this.toggleIsUseRelativePath.bind(this);
+    this.toggleIsUsePamanentLink = this.toggleIsUsePamanentLink.bind(this);
+    this.save = this.save.bind(this);
+    this.generateLink = this.generateLink.bind(this);
+    this.renderPreview = this.renderPreview.bind(this);
+    this.getRootPath = this.getRootPath.bind(this);
+
+    this.getPreviewDebounced = debounce(200, this.getPreview.bind(this));
+  }
+
+  componentDidUpdate(prevState) {
+    const { linkInputValue: prevLinkInputValue } = prevState;
+    const { linkInputValue } = this.state;
+    if (linkInputValue !== prevLinkInputValue) {
+      this.getPreviewDebounced(linkInputValue);
+    }
+  }
+
+  // defaultMarkdownLink is an instance of Linker
+  show(defaultMarkdownLink = null) {
+    // if defaultMarkdownLink is null, set default value in inputs.
+    const { label = '' } = defaultMarkdownLink;
+    let { link = '', type = Linker.types.markdownLink } = defaultMarkdownLink;
+
+    // if type of defaultMarkdownLink is pukiwikiLink when pukiwikiLikeLinker plugin is disable, change type(not change label and link)
+    if (type === Linker.types.pukiwikiLink && !this.isApplyPukiwikiLikeLinkerPlugin) {
+      type = Linker.types.markdownLink;
+    }
+
+    const url = new URL(link, 'http://example.com');
+    const isUseRelativePath = url.origin === 'http://example.com' && !link.startsWith('/') && link !== '';
+    if (isUseRelativePath) {
+      const rootPath = this.getRootPath(type);
+      link = path.resolve(rootPath, link);
+    }
+
+    this.setState({
+      show: true,
+      labelInputValue: label,
+      linkInputValue: link,
+      isUsePermanentLink: false,
+      permalink: '',
+      linkerType: type,
+      isUseRelativePath,
+    });
+  }
+
+  cancel() {
+    this.hide();
+  }
+
+  hide() {
+    this.setState({
+      show: false,
+    });
+  }
+
+  toggleIsUseRelativePath() {
+    if (!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink) {
+      return;
+    }
+
+    // User can't use both relativePath and permalink at the same time
+    this.setState({ isUseRelativePath: !this.state.isUseRelativePath, isUsePermanentLink: false });
+  }
+
+  toggleIsUsePamanentLink() {
+    if (this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink) {
+      return;
+    }
+
+    // User can't use both relativePath and permalink at the same time
+    this.setState({ isUsePermanentLink: !this.state.isUsePermanentLink, isUseRelativePath: false });
+  }
+
+  renderPreview() {
+    return (
+      <div className="linkedit-preview">
+        <Preview
+          markdown={this.state.markdown}
+        />
+      </div>
+    );
+  }
+
+  async getPreview(path) {
+    let markdown = '';
+    let permalink = '';
+    try {
+      const res = await this.props.appContainer.apiGet('/pages.get', { path });
+      markdown = res.page.revision.body;
+      permalink = `${window.location.origin}/${res.page.id}`;
+    }
+    catch (err) {
+      markdown = `<div class="alert alert-warning" role="alert"><strong>${err.message}</strong></div>`;
+    }
+    this.setState({ markdown, permalink });
+  }
+
+  handleChangeTypeahead(selected) {
+    const page = selected[0];
+    if (page != null) {
+      this.setState({ linkInputValue: page.path });
+    }
+  }
+
+  handleChangeLabelInput(label) {
+    this.setState({ labelInputValue: label });
+  }
+
+  handleChangeLinkInput(link) {
+    let isUseRelativePath = this.state.isUseRelativePath;
+    if (!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink) {
+      isUseRelativePath = false;
+    }
+    this.setState({ linkInputValue: link, isUseRelativePath, isUsePermanentLink: false });
+  }
+
+  handleSelecteLinkerType(linkerType) {
+    let { isUseRelativePath, isUsePermanentLink } = this.state;
+    if (linkerType === Linker.types.growiLink) {
+      isUseRelativePath = false;
+      isUsePermanentLink = false;
+    }
+    this.setState({ linkerType, isUseRelativePath, isUsePermanentLink });
+  }
+
+  save() {
+    const output = this.generateLink();
+
+    if (this.props.onSave != null) {
+      this.props.onSave(output);
+    }
+
+    this.hide();
+  }
+
+  generateLink() {
+    const {
+      linkInputValue,
+      labelInputValue,
+      linkerType,
+      isUseRelativePath,
+      isUsePermanentLink,
+      permalink,
+    } = this.state;
+
+    let reshapedLink = linkInputValue;
+    if (isUseRelativePath) {
+      const rootPath = this.getRootPath(linkerType);
+      reshapedLink = rootPath === linkInputValue ? '.' : path.relative(rootPath, linkInputValue);
+    }
+
+    return new Linker(
+      linkerType,
+      labelInputValue,
+      reshapedLink,
+      isUsePermanentLink,
+      permalink,
+    );
+  }
+
+  getRootPath(type) {
+    const { pageContainer } = this.props;
+    const pagePath = pageContainer.state.path;
+    // rootPaths of md link and pukiwiki link are different
+    return type === Linker.types.markdownLink ? path.dirname(pagePath) : pagePath;
+  }
+
+  render() {
+    return (
+      <Modal isOpen={this.state.show} toggle={this.cancel} size="lg">
+        <ModalHeader tag="h4" toggle={this.cancel} className="bg-primary text-light">
+          Edit Links
+        </ModalHeader>
+
+        <ModalBody className="container">
+          <div className="row">
+            <div className="col-12 col-lg-6">
+              <form className="form-group">
+                <div className="form-gorup my-3">
+                  <label htmlFor="linkInput">Link</label>
+                  <div className="input-group">
+                    <SearchTypeahead
+                      onChange={this.handleChangeTypeahead}
+                      onInputChange={this.handleChangeLinkInput}
+                      inputName="link"
+                      placeholder="Input page path or URL"
+                      keywordOnInit={this.state.linkInputValue}
+                    />
+                  </div>
+                </div>
+              </form>
+
+              <div className="d-block d-lg-none mb-3 overflow-auto">
+                {this.renderPreview()}
+              </div>
+
+              <div className="card">
+                <div className="card-body">
+                  <form className="form-group">
+                    <div className="form-group btn-group d-flex" role="group" aria-label="type">
+                      <button
+                        type="button"
+                        name={Linker.types.markdownLink}
+                        className={`btn btn-outline-secondary col ${this.state.linkerType === Linker.types.markdownLink && 'active'}`}
+                        onClick={e => this.handleSelecteLinkerType(e.target.name)}
+                      >
+                        Markdown
+                      </button>
+                      <button
+                        type="button"
+                        name={Linker.types.growiLink}
+                        className={`btn btn-outline-secondary col ${this.state.linkerType === Linker.types.growiLink && 'active'}`}
+                        onClick={e => this.handleSelecteLinkerType(e.target.name)}
+                      >
+                        Growi Original
+                      </button>
+                      {this.isApplyPukiwikiLikeLinkerPlugin && (
+                        <button
+                          type="button"
+                          name={Linker.types.pukiwikiLink}
+                          className={`btn btn-outline-secondary col ${this.state.linkerType === Linker.types.pukiwikiLink && 'active'}`}
+                          onClick={e => this.handleSelecteLinkerType(e.target.name)}
+                        >
+                          Pukiwiki
+                        </button>
+                      )}
+                    </div>
+
+                    <div className="form-group">
+                      <label htmlFor="label">Label</label>
+                      <input
+                        type="text"
+                        className="form-control"
+                        id="label"
+                        value={this.state.labelInputValue}
+                        onChange={e => this.handleChangeLabelInput(e.target.value)}
+                        disabled={this.state.linkerType === Linker.types.growiLink}
+                      />
+                    </div>
+                    <div className="form-inline">
+                      <div className="custom-control custom-checkbox custom-checkbox-info">
+                        <input
+                          className="custom-control-input"
+                          id="relativePath"
+                          type="checkbox"
+                          checked={this.state.isUseRelativePath}
+                          disabled={!this.state.linkInputValue.startsWith('/') || this.state.linkerType === Linker.types.growiLink}
+                        />
+                        <label className="custom-control-label" htmlFor="relativePath" onClick={this.toggleIsUseRelativePath}>
+                          Use relative path
+                        </label>
+                      </div>
+                    </div>
+                    <div className="form-inline">
+                      <div className="custom-control custom-checkbox custom-checkbox-info">
+                        <input
+                          className="custom-control-input"
+                          id="permanentLink"
+                          type="checkbox"
+                          checked={this.state.isUsePermanentLink}
+                          disabled={this.state.permalink === '' || this.state.linkerType === Linker.types.growiLink}
+                        />
+                        <label className="custom-control-label" htmlFor="permanentLink" onClick={this.toggleIsUsePamanentLink}>
+                          Use permanent link
+                        </label>
+                      </div>
+                    </div>
+                  </form>
+                </div>
+              </div>
+            </div>
+
+            <div className="col d-none d-lg-block pr-0 mr-3 overflow-auto">
+              {this.renderPreview()}
+            </div>
+          </div>
+        </ModalBody>
+        <ModalFooter>
+          <button type="button" className="btn btn-sm btn-outline-secondary" onClick={this.hide}>
+            Cancel
+          </button>
+          <button type="submit" className="btn btn-sm btn-primary" onClick={this.save}>
+            Done
+          </button>
+        </ModalFooter>
+      </Modal>
+    );
+  }
+
+}
+
+LinkEditModal.propTypes = {
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
+  onSave: PropTypes.func,
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const LinkEditModalWrapper = withUnstatedContainers(LinkEditModal, [AppContainer, PageContainer]);
+
+export default LinkEditModalWrapper;

+ 3 - 3
src/client/js/components/PageEditor/MarkdownDrawioUtil.js

@@ -139,17 +139,17 @@ class MarkdownDrawioUtil {
    */
   replaceDrawioInMarkdown(drawioData, markdown, beginLineNumber, endLineNumber) {
     const splitMarkdown = markdown.split(/\r\n|\r|\n/);
-    const markdownBeforeDrawio = splitMarkdown.slice(0, beginLineNumber);
+    const markdownBeforeDrawio = splitMarkdown.slice(0, beginLineNumber - 1);
     const markdownAfterDrawio = splitMarkdown.slice(endLineNumber);
 
     let newMarkdown = '';
     if (markdownBeforeDrawio.length > 0) {
       newMarkdown += `${markdownBeforeDrawio.join('\n')}\n`;
-      newMarkdown += '::: drawio\n';
     }
+    newMarkdown += '::: drawio\n';
     newMarkdown += drawioData;
+    newMarkdown += '\n:::';
     if (markdownAfterDrawio.length > 0) {
-      newMarkdown += '\n:::';
       newMarkdown += `\n${markdownAfterDrawio.join('\n')}`;
     }
 

+ 48 - 0
src/client/js/components/PageEditor/MarkdownLinkUtil.js

@@ -0,0 +1,48 @@
+import Linker from '../../models/Linker';
+
+/**
+ * Utility for markdown link
+ */
+class MarkdownLinkUtil {
+
+  constructor() {
+    this.getMarkdownLink = this.getMarkdownLink.bind(this);
+    this.isInLink = this.isInLink.bind(this);
+    this.replaceFocusedMarkdownLinkWithEditor = this.replaceFocusedMarkdownLinkWithEditor.bind(this);
+  }
+
+  // return an instance of Linker from cursor position or selected text.
+  getMarkdownLink(editor) {
+    if (!this.isInLink(editor)) {
+      return Linker.fromMarkdownString(editor.getDoc().getSelection());
+    }
+    const curPos = editor.getCursor();
+    return Linker.fromLineWithIndex(editor.getDoc().getLine(curPos.line), curPos.ch);
+  }
+
+  isInLink(editor) {
+    const curPos = editor.getCursor();
+    const { beginningOfLink, endOfLink } = Linker.getBeginningAndEndIndexOfLink(editor.getDoc().getLine(curPos.line), curPos.ch);
+    return beginningOfLink >= 0 && endOfLink >= 0;
+  }
+
+  // replace link(link is an instance of Linker)
+  replaceFocusedMarkdownLinkWithEditor(editor, link) {
+    const curPos = editor.getCursor();
+    const linkStr = link.generateMarkdownText();
+    if (!this.isInLink(editor)) {
+      editor.getDoc().replaceSelection(linkStr);
+    }
+    else {
+      const line = editor.getDoc().getLine(curPos.line);
+      const { beginningOfLink, endOfLink } = Linker.getBeginningAndEndIndexOfLink(line, curPos.ch);
+      editor.getDoc().replaceRange(linkStr, { line: curPos.line, ch: beginningOfLink }, { line: curPos.line, ch: endOfLink });
+    }
+  }
+
+}
+
+// singleton pattern
+const instance = new MarkdownLinkUtil();
+Object.freeze(instance);
+export default instance;

+ 7 - 2
src/client/js/components/PageHistory.jsx

@@ -26,6 +26,7 @@ class PageHistory extends React.Component {
 
   async componentWillMount() {
     const pageId = this.props.pageId;
+    const shareLinkId = this.props.shareLinkId || null;
 
     if (!pageId) {
       return;
@@ -34,7 +35,7 @@ class PageHistory extends React.Component {
     let res;
     try {
       this.setState({ isLoading: true });
-      res = await this.props.crowi.apiGet('/revisions.ids', { page_id: pageId });
+      res = await this.props.crowi.apiGet('/revisions.ids', { page_id: pageId, share_link_id: shareLinkId });
     }
     catch (err) {
       logger.error(err);
@@ -110,12 +111,14 @@ class PageHistory extends React.Component {
   }
 
   fetchPageRevisionBody(revision) {
+    const shareLinkId = this.props.shareLinkId || null;
+
     if (revision.body) {
       return;
     }
 
     this.props.crowi.apiGet('/revisions.get',
-      { page_id: this.props.pageId, revision_id: revision._id })
+      { page_id: this.props.pageId, revision_id: revision._id, share_link_id: shareLinkId })
       .then((res) => {
         if (res.ok) {
           this.setState({
@@ -166,6 +169,8 @@ class PageHistory extends React.Component {
 
 PageHistory.propTypes = {
   t: PropTypes.func.isRequired, // i18next
+
+  shareLinkId: PropTypes.string,
   pageId: PropTypes.string,
   crowi: PropTypes.object.isRequired,
 };

+ 0 - 2
src/client/js/components/PagePathAutoComplete.jsx

@@ -37,7 +37,6 @@ const PagePathAutoComplete = (props) => {
 
   return (
     <SearchTypeahead
-      crowi={props.crowi}
       onSubmit={submitHandler}
       onChange={inputChangeHandler}
       onInputChange={props.onInputChange}
@@ -51,7 +50,6 @@ const PagePathAutoComplete = (props) => {
 };
 
 PagePathAutoComplete.propTypes = {
-  crowi:            PropTypes.object.isRequired,
   initializedPath:  PropTypes.string,
   addTrailingSlash: PropTypes.bool,
 

+ 1 - 1
src/client/js/components/PageStatusAlert.jsx

@@ -94,7 +94,7 @@ class PageStatusAlert extends React.Component {
 
     // when remote revision is newer than both
     if (isHackmdDocumentOutdated && isRevisionOutdated) {
-      getContentsFunc = this.getContentsFunc;
+      getContentsFunc = this.getContentsForUpdatedAlert;
     }
     // when someone editing with HackMD
     else if (isHackmdDraftUpdatingInRealtime) {

+ 272 - 0
src/client/js/components/ShareLinkForm.jsx

@@ -0,0 +1,272 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+
+import { withTranslation } from 'react-i18next';
+import dateFnsFormat from 'date-fns/format';
+import parse from 'date-fns/parse';
+
+import { isInteger } from 'core-js/fn/number';
+import { withUnstatedContainers } from './UnstatedUtils';
+
+import { toastSuccess, toastError } from '../util/apiNotification';
+
+import AppContainer from '../services/AppContainer';
+import PageContainer from '../services/PageContainer';
+
+class ShareLinkForm extends React.Component {
+
+  constructor(props) {
+    super(props);
+    this.state = {
+      expirationType: 'unlimited',
+      numberOfDays: '7',
+      description: '',
+      customExpirationDate: dateFnsFormat(new Date(), 'yyyy-MM-dd'),
+      customExpirationTime: dateFnsFormat(new Date(), 'hh:mm'),
+    };
+
+    this.handleChangeExpirationType = this.handleChangeExpirationType.bind(this);
+    this.handleChangeNumberOfDays = this.handleChangeNumberOfDays.bind(this);
+    this.handleChangeDescription = this.handleChangeDescription.bind(this);
+    this.handleIssueShareLink = this.handleIssueShareLink.bind(this);
+  }
+
+  /**
+   * change expirationType
+   * @param {string} expirationType
+   */
+  handleChangeExpirationType(expirationType) {
+    this.setState({ expirationType });
+  }
+
+  /**
+   * change numberOfDays
+   * @param {string} numberOfDays
+   */
+  handleChangeNumberOfDays(numberOfDays) {
+    this.setState({ numberOfDays });
+  }
+
+  /**
+   * change description
+   * @param {string} description
+   */
+  handleChangeDescription(description) {
+    this.setState({ description });
+  }
+
+  /**
+   * change customExpirationDate
+   * @param {date} customExpirationDate
+   */
+  handleChangeCustomExpirationDate(customExpirationDate) {
+    this.setState({ customExpirationDate });
+  }
+
+  /**
+   * change customExpirationTime
+   * @param {date} customExpirationTime
+   */
+  handleChangeCustomExpirationTime(customExpirationTime) {
+    this.setState({ customExpirationTime });
+  }
+
+  /**
+   * Generate expiredAt by expirationType
+   */
+  generateExpired() {
+    const { t } = this.props;
+    const { expirationType } = this.state;
+    let expiredAt;
+
+    if (expirationType === 'unlimited') {
+      return null;
+    }
+
+    if (expirationType === 'numberOfDays') {
+      if (!isInteger(Number(this.state.numberOfDays))) {
+        throw new Error(t('share_links.Invalid_Number_of_Date'));
+      }
+      const date = new Date();
+      date.setDate(date.getDate() + Number(this.state.numberOfDays));
+      expiredAt = date;
+    }
+
+    if (expirationType === 'custom') {
+      const { customExpirationDate, customExpirationTime } = this.state;
+      expiredAt = parse(`${customExpirationDate}T${customExpirationTime}`, "yyyy-MM-dd'T'HH:mm", new Date());
+    }
+
+    return expiredAt;
+  }
+
+  closeForm() {
+    const { onCloseForm } = this.props;
+
+    if (onCloseForm == null) {
+      return;
+    }
+    onCloseForm();
+  }
+
+  async handleIssueShareLink() {
+    const {
+      t, appContainer, pageContainer,
+    } = this.props;
+    const { pageId } = pageContainer.state;
+    const { description } = this.state;
+
+    let expiredAt;
+
+    try {
+      expiredAt = this.generateExpired();
+    }
+    catch (err) {
+      return toastError(err);
+    }
+
+    try {
+      await appContainer.apiv3Post('/share-links/', { relatedPage: pageId, expiredAt, description });
+      this.closeForm();
+      toastSuccess(t('toaster.issue_share_link'));
+    }
+    catch (err) {
+      toastError(err);
+    }
+
+  }
+
+  renderExpirationTypeOptions() {
+    const { expirationType } = this.state;
+    const { t } = this.props;
+
+    return (
+      <div className="form-group row">
+        <label htmlFor="inputDesc" className="col-md-5 col-form-label">{t('share_links.expire')}</label>
+        <div className="col-md-7">
+
+
+          <div className="custom-control custom-radio form-group ">
+            <input
+              type="radio"
+              className="custom-control-input"
+              id="customRadio1"
+              name="expirationType"
+              value="customRadio1"
+              checked={expirationType === 'unlimited'}
+              onChange={() => { this.handleChangeExpirationType('unlimited') }}
+            />
+            <label className="custom-control-label" htmlFor="customRadio1">{t('share_links.Unlimited')}</label>
+          </div>
+
+          <div className="custom-control custom-radio  form-group">
+            <input
+              type="radio"
+              className="custom-control-input"
+              id="customRadio2"
+              value="customRadio2"
+              checked={expirationType === 'numberOfDays'}
+              onChange={() => { this.handleChangeExpirationType('numberOfDays') }}
+              name="expirationType"
+            />
+            <label className="custom-control-label" htmlFor="customRadio2">
+              <div className="row align-items-center m-0">
+                <input
+                  type="number"
+                  min="1"
+                  className="col-4"
+                  name="expirationType"
+                  value={this.state.numberOfDays}
+                  onFocus={() => { this.handleChangeExpirationType('numberOfDays') }}
+                  onChange={e => this.handleChangeNumberOfDays(Number(e.target.value))}
+                />
+                <span className="col-auto">{t('share_links.Days')}</span>
+              </div>
+            </label>
+          </div>
+
+          <div className="custom-control custom-radio form-group text-nowrap mb-0">
+            <input
+              type="radio"
+              className="custom-control-input"
+              id="customRadio3"
+              name="expirationType"
+              value="customRadio3"
+              checked={expirationType === 'custom'}
+              onChange={() => { this.handleChangeExpirationType('custom') }}
+            />
+            <label className="custom-control-label" htmlFor="customRadio3">
+              {t('share_links.Custom')}
+            </label>
+            <div className="d-inline-flex flex-wrap">
+              <input
+                type="date"
+                className="ml-3 mb-2"
+                name="customExpirationDate"
+                value={this.state.customExpirationDate}
+                onFocus={() => { this.handleChangeExpirationType('custom') }}
+                onChange={e => this.handleChangeCustomExpirationDate(e.target.value)}
+              />
+              <input
+                type="time"
+                className="ml-3 mb-2"
+                name="customExpiration"
+                value={this.state.customExpirationTime}
+                onFocus={() => { this.handleChangeExpirationType('custom') }}
+                onChange={e => this.handleChangeCustomExpirationTime(e.target.value)}
+              />
+            </div>
+          </div>
+        </div>
+      </div>
+    );
+  }
+
+  renderDescriptionForm() {
+    const { t } = this.props;
+    return (
+      <div className="form-group row">
+        <label htmlFor="inputDesc" className="col-md-5 col-form-label">{t('share_links.description')}</label>
+        <div className="col-md-4">
+          <input
+            type="text"
+            className="form-control"
+            id="inputDesc"
+            placeholder={t('share_links.enter_desc')}
+            value={this.state.description}
+            onChange={e => this.handleChangeDescription(e.target.value)}
+          />
+        </div>
+      </div>
+    );
+  }
+
+  render() {
+    const { t } = this.props;
+    return (
+      <div className="share-link-form p-3">
+        <h3 className="grw-modal-head pb-2"> { t('share_links.share_settings') }</h3>
+        <div className=" p-3">
+          {this.renderExpirationTypeOptions()}
+          {this.renderDescriptionForm()}
+          <button type="button" className="btn btn-primary d-block mx-auto px-5" onClick={this.handleIssueShareLink}>
+            {t('share_links.Issue')}
+          </button>
+        </div>
+      </div>
+    );
+  }
+
+}
+
+const ShareLinkFormWrapper = withUnstatedContainers(ShareLinkForm, [AppContainer, PageContainer]);
+
+ShareLinkForm.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
+
+  onCloseForm: PropTypes.func,
+};
+
+export default withTranslation()(ShareLinkFormWrapper);

+ 79 - 0
src/client/js/components/ShareLinkList.jsx

@@ -0,0 +1,79 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+
+
+import { withTranslation } from 'react-i18next';
+import dateFnsFormat from 'date-fns/format';
+
+import { withUnstatedContainers } from './UnstatedUtils';
+
+import AppContainer from '../services/AppContainer';
+import CopyDropdown from './Page/CopyDropdown';
+
+const ShareLinkList = (props) => {
+
+  const { t } = props;
+  function deleteLinkHandler(shareLinkId) {
+    if (props.onClickDeleteButton == null) {
+      return;
+    }
+    props.onClickDeleteButton(shareLinkId);
+  }
+
+  function renderShareLinks() {
+    return (
+      <>
+        {props.shareLinks.map(shareLink => (
+          <tr key={shareLink._id}>
+            <td>
+              <div className="d-flex">
+                <span className="mr-auto my-auto">{shareLink._id}</span>
+                <CopyDropdown isShareLinkMode pagePath={shareLink.relatedPage.path} pageId={shareLink._id} />
+              </div>
+            </td>
+            {props.isAdmin && <td><a href={shareLink.relatedPage.path}>{shareLink.relatedPage.path}</a></td>}
+            <td>{shareLink.expiredAt && <span>{dateFnsFormat(new Date(shareLink.expiredAt), 'yyyy-MM-dd HH:mm')}</span>}</td>
+            <td>{shareLink.description}</td>
+            <td>
+              <button className="btn btn-outline-warning" type="button" onClick={() => deleteLinkHandler(shareLink._id)}>
+                <i className="icon-trash"></i>{t('Delete')}
+              </button>
+            </td>
+          </tr>
+        ))}
+      </>
+    );
+  }
+
+  return (
+    <div className="table-responsive">
+      <table className="table table-bordered">
+        <thead>
+          <tr>
+            <th>{t('share_links.Share Link')}</th>
+            {props.isAdmin && <th>{t('share_links.Page Path')}</th>}
+            <th>{t('share_links.expire')}</th>
+            <th>{t('share_links.description')}</th>
+            <th></th>
+          </tr>
+        </thead>
+        <tbody>
+          {renderShareLinks()}
+        </tbody>
+      </table>
+    </div>
+  );
+};
+
+const ShareLinkListWrapper = withUnstatedContainers(ShareLinkList, [AppContainer]);
+
+ShareLinkList.propTypes = {
+  t: PropTypes.func.isRequired, //  i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+
+  shareLinks: PropTypes.array.isRequired,
+  onClickDeleteButton: PropTypes.func,
+  isAdmin: PropTypes.bool,
+};
+
+export default withTranslation()(ShareLinkListWrapper);

+ 3 - 1
src/client/js/components/Sidebar.jsx

@@ -159,7 +159,9 @@ class Sidebar extends React.Component {
           calcViewHeightFunc={this.calcViewHeight}
         />
         <div id="grw-sidebar-content-container" className="grw-sidebar-content-container">
-          <SidebarContents />
+          <SidebarContents
+            isSharedUser={this.props.appContainer.isSharedUser}
+          />
         </div>
 
         <DrawerToggler iconClass="icon-arrow-left" />

+ 10 - 1
src/client/js/components/Sidebar/SidebarContents.jsx

@@ -10,8 +10,11 @@ import RecentChanges from './RecentChanges';
 import CustomSidebar from './CustomSidebar';
 
 const SidebarContents = (props) => {
+  const { navigationContainer, isSharedUser } = props;
 
-  const { navigationContainer } = props;
+  if (isSharedUser) {
+    return null;
+  }
 
   let Contents;
   switch (navigationContainer.state.sidebarContentsId) {
@@ -30,6 +33,12 @@ const SidebarContents = (props) => {
 
 SidebarContents.propTypes = {
   navigationContainer: PropTypes.instanceOf(NavigationContainer).isRequired,
+
+  isSharedUser: PropTypes.bool,
+};
+
+SidebarContents.defaultProps = {
+  isSharedUser: false,
 };
 
 /**

+ 3 - 3
src/client/js/components/Sidebar/SidebarNav.jsx

@@ -56,7 +56,7 @@ class SidebarNav extends React.Component {
   }
 
   render() {
-    const { isAdmin, currentUsername } = this.props.appContainer;
+    const { isAdmin, currentUsername, isSharedUser } = this.props.appContainer;
     const isLoggedIn = currentUsername != null;
 
     const { PrimaryItem, SecondaryItem } = this;
@@ -64,8 +64,8 @@ class SidebarNav extends React.Component {
     return (
       <div className="grw-sidebar-nav">
         <div className="grw-sidebar-nav-primary-container">
-          <PrimaryItem id="custom" label="Custom Sidebar" iconName="code" />
-          <PrimaryItem id="recent" label="Recent Changes" iconName="update" />
+          {!isSharedUser && <PrimaryItem id="custom" label="Custom Sidebar" iconName="code" />}
+          {!isSharedUser && <PrimaryItem id="recent" label="Recent Changes" iconName="update" />}
           {/* <PrimaryItem id="tag" label="Tags" iconName="icon-tag" /> */}
           {/* <PrimaryItem id="favorite" label="Favorite" iconName="icon-star" /> */}
         </div>

+ 0 - 1
src/client/js/hackmd-agent.js

@@ -143,7 +143,6 @@ function connectToParentWithPenpal() {
   console.log('[HackMD] Loading GROWI agent for HackMD...');
 
   window.addEventListener('load', (event) => {
-    console.log('loaded');
     addEventListenersToCodemirror();
   });
 

+ 147 - 0
src/client/js/models/Linker.js

@@ -0,0 +1,147 @@
+export default class Linker {
+
+  constructor(
+      type,
+      label,
+      link,
+      isUsePermanentLink = false,
+      permalink = '',
+  ) {
+    this.type = type;
+    this.label = label;
+    this.link = link;
+    this.isUsePermanentLink = isUsePermanentLink;
+    this.permalink = permalink;
+
+    this.generateMarkdownText = this.generateMarkdownText.bind(this);
+  }
+
+  static types = {
+    markdownLink: 'mdLink',
+    growiLink: 'growiLink',
+    pukiwikiLink: 'pukiwikiLink',
+  }
+
+  static patterns = {
+    pukiwikiLinkWithLabel: /^\[\[(?<label>.+)>(?<link>.+)\]\]$/, // https://regex101.com/r/2fNmUN/2
+    pukiwikiLinkWithoutLabel: /^\[\[(?<label>.+)\]\]$/, // https://regex101.com/r/S7w5Xu/1
+    growiLink: /^\[(?<label>\/.+)\]$/, // https://regex101.com/r/DJfkYf/3
+    markdownLink: /^\[(?<label>.*)\]\((?<link>.*)\)$/, // https://regex101.com/r/DZCKP3/2
+  }
+
+  generateMarkdownText() {
+    let reshapedLink = this.link;
+
+    if (this.isUsePermanentLink && this.permalink != null) {
+      reshapedLink = this.permalink;
+    }
+
+    if (this.label === '') {
+      this.label = reshapedLink;
+    }
+
+    if (this.type === Linker.types.pukiwikiLink) {
+      if (this.label === reshapedLink) return `[[${reshapedLink}]]`;
+      return `[[${this.label}>${reshapedLink}]]`;
+    }
+    if (this.type === Linker.types.growiLink) {
+      return `[${reshapedLink}]`;
+    }
+    if (this.type === Linker.types.markdownLink) {
+      return `[${this.label}](${reshapedLink})`;
+    }
+  }
+
+  // create an instance of Linker from string
+  static fromMarkdownString(str) {
+    // if str doesn't mean a linker, create a link whose label is str
+    let label = str;
+    let link = '';
+    let type = this.types.markdownLink;
+
+    // pukiwiki with separator ">".
+    if (str.match(this.patterns.pukiwikiLinkWithLabel)) {
+      type = this.types.pukiwikiLink;
+      ({ label, link } = str.match(this.patterns.pukiwikiLinkWithLabel).groups);
+    }
+    // pukiwiki without separator ">".
+    else if (str.match(this.patterns.pukiwikiLinkWithoutLabel)) {
+      type = this.types.pukiwikiLink;
+      ({ label } = str.match(this.patterns.pukiwikiLinkWithoutLabel).groups);
+      link = label;
+    }
+    // markdown
+    else if (str.match(this.patterns.markdownLink)) {
+      type = this.types.markdownLink;
+      ({ label, link } = str.match(this.patterns.markdownLink).groups);
+    }
+    // growi
+    else if (str.match(this.patterns.growiLink)) {
+      type = this.types.growiLink;
+      ({ label } = str.match(this.patterns.growiLink).groups);
+      link = label;
+    }
+
+    const isUsePermanentLink = false;
+    const permalink = '';
+
+    return new Linker(
+      type,
+      label,
+      link,
+      isUsePermanentLink,
+      permalink,
+    );
+  }
+
+  // create an instance of Linker from text with index
+  static fromLineWithIndex(line, index) {
+    const { beginningOfLink, endOfLink } = this.getBeginningAndEndIndexOfLink(line, index);
+    // if index is in a link, extract it from line
+    let linkStr = '';
+    if (beginningOfLink >= 0 && endOfLink >= 0) {
+      linkStr = line.substring(beginningOfLink, endOfLink);
+    }
+    return this.fromMarkdownString(linkStr);
+  }
+
+  // return beginning and end indexies of link
+  // if index is not in a link, return { beginningOfLink: -1, endOfLink: -1 }
+  static getBeginningAndEndIndexOfLink(line, index) {
+    let beginningOfLink;
+    let endOfLink;
+
+    // pukiwiki link ('[[link]]')
+    [beginningOfLink, endOfLink] = this.getBeginningAndEndIndexWithPrefixAndSuffix(line, index, '[[', ']]');
+
+    // markdown link ('[label](link)')
+    if (beginningOfLink < 0 || endOfLink < 0 || beginningOfLink > index || endOfLink < index) {
+      [beginningOfLink, endOfLink] = this.getBeginningAndEndIndexWithPrefixAndSuffix(line, index, '[', ')', '](');
+    }
+
+    // growi link ('[/link]')
+    if (beginningOfLink < 0 || endOfLink < 0 || beginningOfLink > index || endOfLink < index) {
+      [beginningOfLink, endOfLink] = this.getBeginningAndEndIndexWithPrefixAndSuffix(line, index, '[/', ']');
+    }
+
+    // return { beginningOfLink: -1, endOfLink: -1 }
+    if (beginningOfLink < 0 || endOfLink < 0 || beginningOfLink > index || endOfLink < index) {
+      [beginningOfLink, endOfLink] = [-1, -1];
+    }
+
+    return { beginningOfLink, endOfLink };
+  }
+
+  // return begin and end indexies as array only when index is between prefix and suffix and link contains containText.
+  static getBeginningAndEndIndexWithPrefixAndSuffix(line, index, prefix, suffix, containText = '') {
+    const beginningIndex = line.lastIndexOf(prefix, index);
+    const IndexOfContainText = line.indexOf(containText, beginningIndex + prefix.length);
+    const endIndex = line.indexOf(suffix, IndexOfContainText + containText.length);
+
+    if (beginningIndex < 0 || IndexOfContainText < 0 || endIndex < 0) {
+      return [-1, -1];
+    }
+    return [beginningIndex, endIndex + suffix.length];
+  }
+
+}

+ 13 - 0
src/client/js/services/AdminAppContainer.js

@@ -266,6 +266,19 @@ export default class AdminAppContainer extends Container {
     return mailSettingParams;
   }
 
+  /**
+   * Initialize mail setting
+   * @memberOf AdminAppContainer
+   * @return {Array} Appearance
+   */
+  async initializeMailSettingHandler() {
+    const response = await this.appContainer.apiv3.delete('/app-settings/mail-setting', {});
+    const {
+      mailSettingParams,
+    } = response.data;
+    this.setState(mailSettingParams);
+  }
+
   /**
    * Update AWS setting
    * @memberOf AdminAppContainer

+ 29 - 0
src/client/js/services/AdminGeneralSecurityContainer.js

@@ -30,6 +30,10 @@ export default class AdminGeneralSecurityContainer extends Container {
       isGitHubEnabled: false,
       isTwitterEnabled: false,
       setupStrategies: [],
+      shareLinks: [],
+      totalshareLinks: 0,
+      shareLinksPagingLimit: Infinity,
+      shareLinksActivePage: 1,
     };
 
   }
@@ -151,6 +155,31 @@ export default class AdminGeneralSecurityContainer extends Container {
     }
   }
 
+  /**
+   * Retrieve All Sharelinks
+   */
+  async retrieveShareLinksByPagingNum(page) {
+
+    const params = {
+      page,
+    };
+
+    const { data } = await this.appContainer.apiv3.get('/security-setting/all-share-links', params);
+
+    if (data.paginateResult == null) {
+      throw new Error('data must conclude \'paginateResult\' property.');
+    }
+
+    const { docs: shareLinks, totalDocs: totalshareLinks, limit: shareLinksPagingLimit } = data.paginateResult;
+
+    this.setState({
+      shareLinks,
+      totalshareLinks,
+      shareLinksPagingLimit,
+      shareLinksActivePage: page,
+    });
+  }
+
   /**
    * Switch local enabled
    */

+ 19 - 0
src/client/js/services/AdminSocketIoContainer.js

@@ -0,0 +1,19 @@
+import SocketIoContainer from './SocketIoContainer';
+
+/**
+ * A subclass of SocketIoContainer for /admin namespace
+ */
+export default class AdminSocketIoContainer extends SocketIoContainer {
+
+  constructor(appContainer) {
+    super(appContainer, '/admin');
+  }
+
+  /**
+   * Workaround for the mangling in production build to break constructor.name
+   */
+  static getClassName() {
+    return 'AdminSocketIoContainer';
+  }
+
+}

+ 3 - 0
src/client/js/services/AppContainer.js

@@ -39,6 +39,9 @@ export default class AppContainer extends Container {
 
     this.config = JSON.parse(document.getElementById('growi-context-hydrate').textContent || '{}');
 
+    const isSharedPageElem = document.getElementById('is-shared-page');
+    this.isSharedUser = (isSharedPageElem != null);
+
     const userAgent = window.navigator.userAgent.toLowerCase();
     this.isMobile = /iphone|ipad|android/.test(userAgent);
 

+ 18 - 16
src/client/js/services/PageContainer.js

@@ -64,6 +64,8 @@ export default class PageContainer extends Container {
       tags: null,
       hasChildren: JSON.parse(mainContent.getAttribute('data-page-has-children')),
       templateTagData: mainContent.getAttribute('data-template-tags') || null,
+      shareLinksNumber:  mainContent.getAttribute('data-share-links-number'),
+      shareLinkId: JSON.parse(mainContent.getAttribute('data-share-link-id') || null),
 
       // latest(on remote) information
       remoteRevisionId: revisionId,
@@ -314,11 +316,11 @@ export default class PageContainer extends Container {
   }
 
   async createPage(pagePath, markdown, tmpParams) {
-    const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
+    const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
 
     // clone
     const params = Object.assign(tmpParams, {
-      socketClientId: websocketContainer.getSocketClientId(),
+      socketClientId: socketIoContainer.getSocketClientId(),
       path: pagePath,
       body: markdown,
     });
@@ -331,11 +333,11 @@ export default class PageContainer extends Container {
   }
 
   async updatePage(pageId, revisionId, markdown, tmpParams) {
-    const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
+    const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
 
     // clone
     const params = Object.assign(tmpParams, {
-      socketClientId: websocketContainer.getSocketClientId(),
+      socketClientId: socketIoContainer.getSocketClientId(),
       page_id: pageId,
       revision_id: revisionId,
       body: markdown,
@@ -349,7 +351,7 @@ export default class PageContainer extends Container {
   }
 
   deletePage(isRecursively, isCompletely) {
-    const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
+    const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
 
     // control flag
     const completely = isCompletely ? true : null;
@@ -360,13 +362,13 @@ export default class PageContainer extends Container {
       completely,
       page_id: this.state.pageId,
       revision_id: this.state.revisionId,
-      socketClientId: websocketContainer.getSocketClientId(),
+      socketClientId: socketIoContainer.getSocketClientId(),
     });
 
   }
 
   revertRemove(isRecursively) {
-    const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
+    const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
 
     // control flag
     const recursively = isRecursively ? true : null;
@@ -374,12 +376,12 @@ export default class PageContainer extends Container {
     return this.appContainer.apiPost('/pages.revertRemove', {
       recursively,
       page_id: this.state.pageId,
-      socketClientId: websocketContainer.getSocketClientId(),
+      socketClientId: socketIoContainer.getSocketClientId(),
     });
   }
 
   rename(pageNameInput, isRenameRecursively, isRenameRedirect, isRenameMetadata) {
-    const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
+    const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
     const isRecursively = isRenameRecursively ? true : null;
     const isRedirect = isRenameRedirect ? true : null;
     const isRemain = isRenameMetadata ? true : null;
@@ -391,7 +393,7 @@ export default class PageContainer extends Container {
       new_path: pageNameInput,
       create_redirect: isRedirect,
       remain_metadata: isRemain,
-      socketClientId: websocketContainer.getSocketClientId(),
+      socketClientId: socketIoContainer.getSocketClientId(),
     });
   }
 
@@ -420,12 +422,12 @@ export default class PageContainer extends Container {
 
   addWebSocketEventHandlers() {
     const pageContainer = this;
-    const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
-    const socket = websocketContainer.getWebSocket();
+    const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
+    const socket = socketIoContainer.getSocket();
 
     socket.on('page:create', (data) => {
       // skip if triggered myself
-      if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
+      if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
         return;
       }
 
@@ -439,7 +441,7 @@ export default class PageContainer extends Container {
 
     socket.on('page:update', (data) => {
       // skip if triggered myself
-      if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
+      if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
         return;
       }
 
@@ -460,7 +462,7 @@ export default class PageContainer extends Container {
 
     socket.on('page:delete', (data) => {
       // skip if triggered myself
-      if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
+      if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
         return;
       }
 
@@ -474,7 +476,7 @@ export default class PageContainer extends Container {
 
     socket.on('page:editingWithHackmd', (data) => {
       // skip if triggered myself
-      if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
+      if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
         return;
       }
 

+ 9 - 5
src/client/js/services/WebsocketContainer.js → src/client/js/services/SocketIoContainer.js

@@ -6,15 +6,19 @@ import io from 'socket.io-client';
  * Service container related to options for WebSocket
  * @extends {Container} unstated Container
  */
-export default class WebsocketContainer extends Container {
+export default class SocketIoContainer extends Container {
 
-  constructor(appContainer) {
+  constructor(appContainer, namespace) {
     super();
 
     this.appContainer = appContainer;
     this.appContainer.registerContainer(this);
 
-    this.socket = io();
+    const ns = namespace || '/';
+
+    this.socket = io(ns, {
+      transports: ['websocket'],
+    });
     this.socketClientId = Math.floor(Math.random() * 100000);
 
     this.state = {
@@ -26,10 +30,10 @@ export default class WebsocketContainer extends Container {
    * Workaround for the mangling in production build to break constructor.name
    */
   static getClassName() {
-    return 'WebsocketContainer';
+    return 'SocketIoContainer';
   }
 
-  getWebSocket() {
+  getSocket() {
     return this.socket;
   }
 

+ 0 - 16
src/client/js/util/interceptor/drawio-interceptor.js

@@ -18,22 +18,6 @@ export class DrawioInterceptor extends BasicInterceptor {
 
     this.previousPreviewContext = null;
     this.appContainer = appContainer;
-
-    // define callback function invoked by viewer.min.js of draw.io
-    // refs: https://github.com/jgraph/drawio/blob/v12.9.1/etc/build/build.xml#L219-L232
-    window.onDrawioViewerLoad = function() {
-      const DrawioViewer = window.GraphViewer;
-
-      if (DrawioViewer != null) {
-        // disable useResizeSensor and checkVisibleState
-        //   for preventing resize event by viewer.min.js
-        DrawioViewer.useResizeSensor = false;
-        DrawioViewer.prototype.checkVisibleState = false;
-
-        // initialize
-        DrawioViewer.processElements();
-      }
-    };
   }
 
   /**

+ 1 - 6
src/client/styles/scss/_layout_kibela.scss

@@ -5,11 +5,6 @@ body.kibela {
     padding-top: 10px !important;
   }
 
-  /* navbar for kibela */
-  #page-wrapper {
-    margin-top: $grw-navbar-height + $grw-navbar-border-width;
-  }
-
   /* Logo */
   .logo {
     .logo-mark {
@@ -51,7 +46,7 @@ body.kibela {
 
   .kibela-block {
     position: relative;
-    top: 10px;
+    top: 30px;
     right: 100px;
     bottom: 0px;
     left: 0px;

+ 8 - 0
src/client/styles/scss/_linkedit-preview.scss

@@ -0,0 +1,8 @@
+.modal .modal-body .linkedit-preview {
+  height: 0;
+  padding-bottom: 50%;
+
+  .page-editor-preview-body {
+    overflow-y: unset;
+  }
+}

+ 23 - 10
src/client/styles/scss/_on-edit.scss

@@ -187,19 +187,32 @@ body.on-edit {
       }
 
       // add icon on cursor
+      .markdown-table-activated, .markdown-link-activated {
+        .CodeMirror-cursor {
+          &:after {
+            position: relative;
+            top: -1.1em;
+            left: 0.3em;
+            display: block;
+            width: 1em;
+            height: 1em;
+            content: ' ';
+  
+            background-repeat: no-repeat;
+            background-size: 1em;
+          }
+        }
+      }
+
       .markdown-table-activated .CodeMirror-cursor {
         &:after {
-          position: relative;
-          top: -1.1em;
-          left: 0.3em;
-          display: block;
-          width: 1em;
-          height: 1em;
-          content: ' ';
-
           background-image: url(/images/icons/editor/table.svg);
-          background-repeat: no-repeat;
-          background-size: 1em;
+        }
+      }
+
+      .markdown-link-activated .CodeMirror-cursor {
+        &:after {
+          background-image: url(/images/icons/editor/link.svg);
         }
       }
 

+ 12 - 0
src/client/styles/scss/_override-bootstrap-variables.scss

@@ -12,6 +12,18 @@ $warning: #ffa32b !default;
 $danger: #ff0a54 !default;
 $light: #e4e7ea !default;
 $dark: #343a40 !default;
+$gray-50: lighten($light, 7%) !default;
+$gray-100: lighten($light, 4%) !default;
+$gray-200: $light !default;
+$gray-300: darken($light, 5%) !default;
+$gray-400: darken($light, 20%) !default;
+$gray-500: darken($light, 30%) !default;
+$gray-600: lighten($dark, 10%) !default;
+$gray-700: lighten($dark, 5%) !default;
+$gray-800: $dark !default;
+$gray-900: darken($dark, 5%) !default;
+$grays: ("50": $gray-50) !default;
+$red: #ff0a54 !default;
 
 //== Typography
 //

+ 2 - 0
src/client/styles/scss/_override-bootstrap.scss

@@ -79,7 +79,9 @@
   // Dropdowns
   .dropdown-toggle {
     &.btn.disabled {
+      pointer-events: auto;
       cursor: not-allowed;
+      opacity: unset;
     }
 
     // hide caret

+ 4 - 4
src/client/styles/scss/_search.scss

@@ -193,12 +193,12 @@
   }
 
   .search-result-content {
-    padding-bottom: 32px;
+    padding-bottom: 36px;
 
     .search-result-page {
-      padding-top: 48px;
+      padding-top: 64px;
       // adjust for anchor links by the height of fixed .search-page-input
-      margin-top: -48px;
+      margin-top: -64px;
 
       > h2 {
         margin-right: 10px;
@@ -221,7 +221,7 @@
 
 .search-page-input {
   position: sticky;
-  top: 65px;
+  top: 15px;
   // placed at front-most
   z-index: 15;
 

+ 12 - 0
src/client/styles/scss/_sharelink.scss

@@ -0,0 +1,12 @@
+.share-link-form {
+  /* Chrome/Safari */
+  input[type='number']::-webkit-outer-spin-button,
+  input[type='number']::-webkit-inner-spin-button {
+    -webkit-appearance: none;
+  }
+
+  /* Firefox */
+  input[type='number'] {
+    -moz-appearance: textfield;
+  }
+}

+ 1 - 0
src/client/styles/scss/_sidebar.scss

@@ -82,6 +82,7 @@
   }
 
   .grw-sidebar-nav {
+    min-width: 62px;
     height: 100vh;
 
     .btn {

+ 2 - 0
src/client/styles/scss/style-app.scss

@@ -60,6 +60,8 @@
 @import 'staff_credit';
 @import 'waves';
 @import 'wiki';
+@import 'sharelink';
+@import 'linkedit-preview';
 
 /*
  * for Guest User Mode

+ 11 - 11
src/client/styles/scss/theme/_apply-colors-light.scss

@@ -8,15 +8,15 @@ $bgcolor-list-active: $primary !default;
 $bgcolor-subnav: darken($bgcolor-global, 3%) !default;
 $color-table: $color-global !default;
 $bgcolor-table: null !default;
-$border-color-table: #dee2e6 !default;
+$border-color-table: $gray-200 !default;
 $color-table-hover: $color-table !default;
 $bgcolor-table-hover: rgba(black, 0.075) !default;
 $bgcolor-sidebar-list-group: $bgcolor-list !default;
-$color-tags: #949494 !default;
-$bgcolor-tags: #ebebeb !default;
+$color-tags: $gray-500 !default;
+$bgcolor-tags: $gray-200 !default;
 
 // override bootstrap variables
-$border-color: #dee2e6;
+$border-color: $gray-200;
 $table-color: $color-table;
 $table-bg: $bgcolor-table;
 $table-border-color: $border-color-table;
@@ -72,28 +72,28 @@ $table-hover-bg: $bgcolor-table-hover;
   .dropdown-with-icon {
     .dropdown-toggle {
       color: white;
-      background-color: rgba(#505050, 0.7);
+      background-color: rgba($gray-600, 0.7);
       box-shadow: unset;
       &:focus {
         color: white;
-        background-color: rgba(#505050, 0.7);
+        background-color: rgba($gray-600, 0.7);
       }
     }
     i {
       color: darken(white, 30%);
-      background-color: rgba(#444, 0.7);
+      background-color: rgba($gray-700, 0.7);
     }
   }
 
   .input-group {
     .input-group-text {
       color: darken(white, 30%);
-      background-color: rgba(#444, 0.7);
+      background-color: rgba($gray-700, 0.7);
     }
 
     .form-control {
       color: white;
-      background-color: rgba(#505050, 0.7);
+      background-color: rgba($gray-600, 0.7);
       box-shadow: unset;
 
       &::placeholder {
@@ -134,7 +134,7 @@ $table-hover-bg: $bgcolor-table-hover;
 
 .grw-drawer-toggler {
   @extend .btn-light;
-  color: #999;
+  color: $gray-500;
 }
 
 /*
@@ -176,7 +176,7 @@ $table-hover-bg: $bgcolor-table-hover;
 
 .wiki {
   h1 {
-    border-color: darken($border-color-theme, 10%);
+    border-color: $border-color-theme;
   }
   h2 {
     border-color: $border-color-theme;

+ 8 - 8
src/client/styles/scss/theme/_apply-colors.scss

@@ -3,16 +3,16 @@
 //
 
 // determine optional variables
-$border-image-navbar: linear-gradient(to right, #ccc 0%, #ccc 100%) !default;
+$border-image-navbar: linear-gradient(to right, $gray-300 0%, $gray-300 100%) !default;
 $bgcolor-search-top-dropdown: $secondary !default;
 $bgcolor-sidebar-nav-item-active: darken($bgcolor-sidebar, 10%) !default;
 $text-shadow-sidebar-nav-item-active: 1px 1px 2px $primary !default;
-$bgcolor-inline-code: #f0f0f0 !default;
-$color-inline-code: #c7254e !default;
-$bordercolor-inline-code: #ccc8c8 !default;
-$bordercolor-nav-tabs: #dee2e6 !default;
-$bordercolor-nav-tabs-hover: #e9ecef #e9ecef $bordercolor-nav-tabs !default;
-$color-nav-tabs-link-active: #495057 !default;
+$bgcolor-inline-code: $gray-100 !default;
+$color-inline-code: darken($red, 15%) !default;
+$bordercolor-inline-code: $gray-400 !default;
+$bordercolor-nav-tabs: $gray-300 !default;
+$bordercolor-nav-tabs-hover: $gray-200 $gray-200 $bordercolor-nav-tabs !default;
+$color-nav-tabs-link-active: $gray-600 !default;
 $bordercolor-nav-tabs-active: $bordercolor-nav-tabs $bordercolor-nav-tabs $bgcolor-global !default;
 
 // override bootstrap variables
@@ -264,7 +264,7 @@ pre:not(.hljs):not(.CodeMirror-line) {
  */
 .admin-page {
   span.slider {
-    background-color: #ccc;
+    background-color: $gray-300;
 
     &:before {
       background-color: white;

+ 15 - 14
src/client/styles/scss/theme/default.scss

@@ -16,22 +16,23 @@
 //
 html[light] {
   $primary: #122c55;
+  $accent: #209fd8;
 
   // Background colors
   $bgcolor-global: white;
-  $bgcolor-inline-code: #f0f0f0; //optional
-  $bgcolor-card: #f5f5f5;
+  $bgcolor-inline-code: $gray-100; //optional
+  $bgcolor-card: $gray-50;
 
   // Font colors
   $color-global: #112744;
-  $color-reversal: #eeeeee;
+  $color-reversal: $light;
   // $color-header: #2b2b2b;
   $color-link: #1938ba;
   $color-link-hover: lighten($color-link, 20%);
   $color-link-wiki: $color-link;
   $color-link-wiki-hover: lighten($color-link-wiki, 20%);
-  $color-link-nabvar: #a7a7a7;
-  $color-inline-code: #c7254e; // optional
+  $color-link-nabvar: $gray-500;
+  $color-inline-code: darken($red, 15%); // optional
 
   // List Group colors
   // $color-list: $color-global; // optional
@@ -50,8 +51,8 @@ html[light] {
   // $bgcolor-table-hover: #; // optional
 
   // Navbar
-  $bgcolor-navbar: #2a2929;
-  $bgcolor-search-top-dropdown: #209fd8;
+  $bgcolor-navbar: $gray-900;
+  $bgcolor-search-top-dropdown: $accent;
   $border-image-navbar: linear-gradient(to right, #36c9ff 0%, #36c9ff 33%, #7926ff 66%, #ff2eff 100%);
 
   // Logo colors
@@ -59,19 +60,19 @@ html[light] {
   $fillcolor-logo-mark: lighten(desaturate($bgcolor-navbar, 10%), 15%);
 
   // Sidebar
-  $bgcolor-sidebar: #122c55;
-  $bgcolor-sidebar-nav-item-active: rgba(#000000, 0.37); // optional
+  $bgcolor-sidebar: $primary;
+  $bgcolor-sidebar-nav-item-active: rgba(black, 0.37); // optional
   $text-shadow-sidebar-nav-item-active: 0px 0px 10px #0099ff; // optional
   // Sidebar resize button
   $color-resize-button: $color-reversal;
-  $bgcolor-resize-button: #209fd8;
+  $bgcolor-resize-button: $accent;
   $color-resize-button-hover: $color-reversal;
   $bgcolor-resize-button-hover: lighten($bgcolor-resize-button, 5%);
   // Sidebar contents
   $color-sidebar-context: $color-global;
-  $bgcolor-sidebar-context: #f4f6fc;
+  $bgcolor-sidebar-context: $gray-100;
   // Sidebar list group
-  $bgcolor-sidebar-list-group: #fafbff; // optional
+  $bgcolor-sidebar-list-group: $gray-50; // optional
 
   // Subnavigation
   // $bgcolor-subnav: #fafafa; // optional
@@ -89,8 +90,8 @@ html[light] {
   $color-editor-icons: $color-global;
 
   // Border colors
-  $border-color-theme: #ccc;
-  $bordercolor-inline-code: #ccc8c8; // optional
+  $border-color-theme: $gray-400;
+  $bordercolor-inline-code: $gray-400; // optional
 
   // Dropdown colors
   $bgcolor-dropdown-link-active: $growi-blue;

+ 2 - 2
src/server/crowi/express-init.js

@@ -20,7 +20,7 @@ module.exports = function(crowi, app) {
 
   const registerSafeRedirect = require('../middlewares/safe-redirect')();
   const injectCurrentuserToLocalvars = require('../middlewares/inject-currentuser-to-localvars')();
-  const autoReconnectToConfigPubsub = require('../middlewares/auto-reconnect-to-config-pubsub')(crowi);
+  const autoReconnectToS2sMsgServer = require('../middlewares/auto-reconnect-to-s2s-msg-server')(crowi);
   const { listLocaleIds } = require('@commons/util/locale-utils');
 
   const avoidSessionRoutes = require('../routes/avoid-session-routes');
@@ -118,7 +118,7 @@ module.exports = function(crowi, app) {
 
   app.use(registerSafeRedirect);
   app.use(injectCurrentuserToLocalvars);
-  app.use(autoReconnectToConfigPubsub);
+  app.use(autoReconnectToS2sMsgServer);
 
   const middlewares = require('../util/middlewares')(crowi, app);
   app.use(middlewares.swigFilters(swig));

+ 57 - 29
src/server/crowi/index.js

@@ -1,5 +1,3 @@
-
-
 const debug = require('debug')('growi:crowi');
 const logger = require('@alias/logger')('growi:crowi');
 const pkg = require('@root/package.json');
@@ -10,14 +8,14 @@ const { getMongoUri, mongoOptions } = require('@commons/util/mongoose-utils');
 
 const path = require('path');
 
-const sep = path.sep;
-
 const mongoose = require('mongoose');
 
 const models = require('../models');
 
 const PluginService = require('../plugins/plugin.service');
 
+const sep = path.sep;
+
 function Crowi(rootdir) {
   const self = this;
 
@@ -39,6 +37,7 @@ function Crowi(rootdir) {
 
   this.config = {};
   this.configManager = null;
+  this.s2sMessagingService = null;
   this.mailService = null;
   this.passportService = null;
   this.globalNotificationService = null;
@@ -52,6 +51,9 @@ function Crowi(rootdir) {
   this.exportService = null;
   this.importService = null;
   this.searchService = null;
+  this.socketIoService = null;
+  this.pageService = null;
+  this.syncPageStatusService = null;
   this.cdnResourcesService = new CdnResourcesService();
   this.interceptorManager = new InterceptorManager();
   this.xss = new Xss();
@@ -68,7 +70,6 @@ function Crowi(rootdir) {
   this.events = {
     user: new (require(`${self.eventsDir}user`))(this),
     page: new (require(`${self.eventsDir}page`))(this),
-    search: new (require(`${self.eventsDir}search`))(this),
     bookmark: new (require(`${self.eventsDir}bookmark`))(this),
     tag: new (require(`${self.eventsDir}tag`))(this),
     admin: new (require(`${self.eventsDir}admin`))(this),
@@ -81,6 +82,10 @@ Crowi.prototype.init = async function() {
   await this.setupSessionConfig();
   await this.setupConfigManager();
 
+  // setup messaging services
+  await this.setupS2sMessagingService();
+  await this.setupSocketIoService();
+
   // customizeService depends on AppService and XssService
   // passportService depends on appService
   // slack depends on setUpSlacklNotification
@@ -106,6 +111,8 @@ Crowi.prototype.init = async function() {
     this.setupUserGroup(),
     this.setupExport(),
     this.setupImport(),
+    this.setupPageService(),
+    this.setupSyncPageStatusService(),
   ]);
 
   // globalNotification depends on slack and mailer
@@ -251,15 +258,25 @@ Crowi.prototype.setupSessionConfig = async function() {
 Crowi.prototype.setupConfigManager = async function() {
   const ConfigManager = require('../service/config-manager');
   this.configManager = new ConfigManager(this.model('Config'));
-  await this.configManager.loadConfigs();
+  return this.configManager.loadConfigs();
+};
 
-  // setup pubsub
-  this.configPubsub = require('../service/config-pubsub')(this);
-  if (this.configPubsub != null) {
-    this.configPubsub.subscribe();
-    this.configManager.setPubsub(this.configPubsub);
+Crowi.prototype.setupS2sMessagingService = async function() {
+  const s2sMessagingService = require('../service/s2s-messaging')(this);
+  if (s2sMessagingService != null) {
+    s2sMessagingService.subscribe();
+    this.configManager.setS2sMessagingService(s2sMessagingService);
     // add as a message handler
-    this.configPubsub.addMessageHandler(this.configManager);
+    s2sMessagingService.addMessageHandler(this.configManager);
+
+    this.s2sMessagingService = s2sMessagingService;
+  }
+};
+
+Crowi.prototype.setupSocketIoService = async function() {
+  const SocketIoService = require('../service/socket-io');
+  if (this.socketIoService == null) {
+    this.socketIoService = new SocketIoService();
   }
 };
 
@@ -269,10 +286,6 @@ Crowi.prototype.setupModels = async function() {
   });
 };
 
-Crowi.prototype.getIo = function() {
-  return this.io;
-};
-
 Crowi.prototype.scanRuntimeVersions = async function() {
   const self = this;
 
@@ -329,8 +342,8 @@ Crowi.prototype.setupPassport = async function() {
   }
 
   // add as a message handler
-  if (this.configPubsub != null) {
-    this.configPubsub.addMessageHandler(this.passportService);
+  if (this.s2sMessagingService != null) {
+    this.s2sMessagingService.addMessageHandler(this.passportService);
   }
 
   return Promise.resolve();
@@ -346,8 +359,8 @@ Crowi.prototype.setupMailer = async function() {
   this.mailService = new MailService(this);
 
   // add as a message handler
-  if (this.configPubsub != null) {
-    this.configPubsub.addMessageHandler(this.mailService);
+  if (this.s2sMessagingService != null) {
+    this.s2sMessagingService.addMessageHandler(this.mailService);
   }
 };
 
@@ -398,11 +411,7 @@ Crowi.prototype.start = async function() {
     }
   });
 
-  // setup WebSocket
-  const io = require('socket.io')(serverListening);
-  io.sockets.on('connection', (socket) => {
-  });
-  this.io = io;
+  this.socketIoService.attachServer(serverListening);
 
   // setup Express Routes
   this.setupRoutesAtLast();
@@ -510,8 +519,8 @@ Crowi.prototype.setUpCustomize = async function() {
     this.customizeService.initCustomTitle();
 
     // add as a message handler
-    if (this.configPubsub != null) {
-      this.configPubsub.addMessageHandler(this.customizeService);
+    if (this.s2sMessagingService != null) {
+      this.s2sMessagingService.addMessageHandler(this.customizeService);
     }
   }
 };
@@ -526,8 +535,8 @@ Crowi.prototype.setUpApp = async function() {
 
     // add as a message handler
     const isInstalled = this.configManager.getConfig('crowi', 'app:installed');
-    if (this.configPubsub != null && !isInstalled) {
-      this.configPubsub.addMessageHandler(this.appService);
+    if (this.s2sMessagingService != null && !isInstalled) {
+      this.s2sMessagingService.addMessageHandler(this.appService);
     }
   }
 };
@@ -580,4 +589,23 @@ Crowi.prototype.setupImport = async function() {
   }
 };
 
+Crowi.prototype.setupPageService = async function() {
+  const PageEventService = require('../service/page');
+  if (this.pageService == null) {
+    this.pageService = new PageEventService(this);
+  }
+};
+
+Crowi.prototype.setupSyncPageStatusService = async function() {
+  const SyncPageStatusService = require('../service/system-events/sync-page-status');
+  if (this.syncPageStatusService == null) {
+    this.syncPageStatusService = new SyncPageStatusService(this, this.s2sMessagingService, this.socketIoService);
+
+    // add as a message handler
+    if (this.s2sMessagingService != null) {
+      this.s2sMessagingService.addMessageHandler(this.syncPageStatusService);
+    }
+  }
+};
+
 module.exports = Crowi;

+ 0 - 11
src/server/events/search.js

@@ -1,11 +0,0 @@
-const util = require('util');
-const events = require('events');
-
-function SearchEvent(crowi) {
-  this.crowi = crowi;
-
-  events.EventEmitter.call(this);
-}
-util.inherits(SearchEvent, events.EventEmitter);
-
-module.exports = SearchEvent;

+ 0 - 11
src/server/middlewares/auto-reconnect-to-config-pubsub.js

@@ -1,11 +0,0 @@
-module.exports = (crowi) => {
-  const { configPubsub } = crowi;
-
-  return (req, res, next) => {
-    if (configPubsub != null && configPubsub.shouldResubscribe()) {
-      configPubsub.subscribe();
-    }
-
-    return next();
-  };
-};

+ 11 - 0
src/server/middlewares/auto-reconnect-to-s2s-msg-server.js

@@ -0,0 +1,11 @@
+module.exports = (crowi) => {
+  const { s2sMessagingService } = crowi;
+
+  return (req, res, next) => {
+    if (s2sMessagingService != null && s2sMessagingService.shouldResubscribe()) {
+      s2sMessagingService.subscribe();
+    }
+
+    return next();
+  };
+};

+ 46 - 0
src/server/middlewares/certify-shared-file.js

@@ -0,0 +1,46 @@
+const loggerFactory = require('@alias/logger');
+const url = require('url');
+
+const logger = loggerFactory('growi:middleware:certify-shared-fire');
+
+module.exports = (crowi) => {
+
+  return async(req, res, next) => {
+    const { referer } = req.headers;
+    const { path } = url.parse(referer);
+
+    if (!path.startsWith('/share/')) {
+      next();
+    }
+
+    const fileId = req.params.id || null;
+
+    const Attachment = crowi.model('Attachment');
+    const ShareLink = crowi.model('ShareLink');
+
+    const attachment = await Attachment.findOne({ _id: fileId });
+
+    if (attachment == null) {
+      next();
+    }
+
+    const shareLinks = await ShareLink.find({ relatedPage: attachment.page });
+
+    // If sharelinks don't exist, skip it
+    if (shareLinks.length === 0) {
+      next();
+    }
+
+    // Is there a valid share link
+    shareLinks.map((sharelink) => {
+      if (!sharelink.isExpired()) {
+        logger.debug('Confirmed target file belong to a share page');
+        req.isSharedPage = true;
+      }
+      return;
+    });
+
+    next();
+  };
+
+};

+ 31 - 0
src/server/middlewares/certify-shared-page.js

@@ -0,0 +1,31 @@
+const loggerFactory = require('@alias/logger');
+
+const logger = loggerFactory('growi:middleware:certify-shared-page');
+
+module.exports = (crowi) => {
+
+  return async(req, res, next) => {
+    const pageId = req.query.page_id || req.body.page_id || null;
+    const shareLinkId = req.query.share_link_id || req.body.share_link_id || null;
+    if (pageId == null || shareLinkId == null) {
+      return next();
+    }
+
+    const ShareLink = crowi.model('ShareLink');
+    const sharelink = await ShareLink.findOne({ _id: shareLinkId, relatedPage: pageId });
+
+    // check sharelink enabled
+    if (sharelink == null || sharelink.isExpired()) {
+      return next();
+    }
+
+    logger.debug('shareLink id is', sharelink._id);
+
+    req.isSharedPage = true;
+
+    logger.debug('Confirmed target page id is a share page');
+
+    next();
+  };
+
+};

+ 6 - 0
src/server/middlewares/login-required.js

@@ -17,6 +17,12 @@ module.exports = (crowi, isGuestAllowed = false) => {
       return next();
     }
 
+    // check the page is shared
+    if (isGuestAllowed && req.isSharedPage) {
+      logger.debug('Target page is shared page');
+      return next();
+    }
+
     const User = crowi.model('User');
 
     // check the user logged in

+ 1 - 0
src/server/models/index.js

@@ -15,4 +15,5 @@ module.exports = {
   GlobalNotificationSetting: require('./GlobalNotificationSetting'),
   GlobalNotificationMailSetting: require('./GlobalNotificationSetting/GlobalNotificationMailSetting'),
   GlobalNotificationSlackSetting: require('./GlobalNotificationSetting/GlobalNotificationSlackSetting'),
+  ShareLink: require('./share-link'),
 };

+ 45 - 35
src/server/models/page.js

@@ -702,6 +702,32 @@ module.exports = function(crowi) {
     return await findListFromBuilderAndViewer(builder, user, false, option);
   };
 
+  /**
+   * find pages that is match with `path` and its descendants whitch user is able to manage
+   */
+  pageSchema.statics.findManageableListWithDescendants = async function(page, user, option = {}) {
+    if (user == null) {
+      return null;
+    }
+
+    const builder = new PageQueryBuilder(this.find());
+    builder.addConditionToListWithDescendants(page.path, option);
+    builder.addConditionToExcludeRedirect();
+
+    // add grant conditions
+    await addConditionToFilteringByViewerToEdit(builder, user);
+
+    const { pages } = await findListFromBuilderAndViewer(builder, user, false, option);
+
+    // add page if 'grant' is GRANT_RESTRICTED
+    // because addConditionToListWithDescendants excludes GRANT_RESTRICTED pages
+    if (page.grant === GRANT_RESTRICTED) {
+      pages.push(page);
+    }
+
+    return pages;
+  };
+
   /**
    * find pages that start with `path`
    */
@@ -1096,14 +1122,8 @@ module.exports = function(crowi) {
       throw new Error('This method does NOT supports deleting trashed pages.');
     }
 
-    // find descendants (this array does not include GRANT_RESTRICTED)
-    const result = await this.findListWithDescendants(targetPage.path, user);
-    const pages = result.pages;
-    // add targetPage if 'grant' is GRANT_RESTRICTED
-    //  because findListWithDescendants excludes GRANT_RESTRICTED pages
-    if (targetPage.grant === GRANT_RESTRICTED) {
-      pages.push(targetPage);
-    }
+    // find manageable descendants (this array does not include GRANT_RESTRICTED)
+    const pages = await this.findManageableListWithDescendants(targetPage, user, options);
 
     await Promise.all(pages.map((page) => {
       return this.deletePage(page, user, options);
@@ -1135,8 +1155,7 @@ module.exports = function(crowi) {
 
   pageSchema.statics.revertDeletedPageRecursively = async function(targetPage, user, options = {}) {
     const findOpts = { includeTrashed: true };
-    const result = await this.findListWithDescendants(targetPage.path, user, findOpts);
-    const pages = result.pages;
+    const pages = await this.findManageableListWithDescendants(targetPage, user, findOpts);
 
     let updatedPage = null;
     await Promise.all(pages.map((page) => {
@@ -1162,19 +1181,24 @@ module.exports = function(crowi) {
     const Attachment = crowi.model('Attachment');
     const Comment = crowi.model('Comment');
     const PageTagRelation = crowi.model('PageTagRelation');
+    const ShareLink = crowi.model('ShareLink');
     const Revision = crowi.model('Revision');
     const pageId = pageData._id;
     const socketClientId = options.socketClientId || null;
 
     debug('Completely delete', pageData.path);
 
-    await Bookmark.removeBookmarksByPageId(pageId);
-    await Attachment.removeAttachmentsByPageId(pageId);
-    await Comment.removeCommentsByPageId(pageId);
-    await PageTagRelation.remove({ relatedPage: pageId });
-    await Revision.removeRevisionsByPath(pageData.path);
-    await this.findByIdAndRemove(pageId);
-    await this.removeRedirectOriginPageByPath(pageData.path);
+    await Promise.all([
+      Bookmark.removeBookmarksByPageId(pageId),
+      Attachment.removeAttachmentsByPageId(pageId),
+      Comment.removeCommentsByPageId(pageId),
+      PageTagRelation.remove({ relatedPage: pageId }),
+      ShareLink.remove({ relatedPage: pageId }),
+      Revision.removeRevisionsByPath(pageData.path),
+      this.findByIdAndRemove(pageId),
+      this.removeRedirectOriginPageByPath(pageData.path),
+    ]);
+
     if (socketClientId != null) {
       pageEvent.emit('delete', pageData, user, socketClientId); // update as renamed page
     }
@@ -1185,18 +1209,10 @@ module.exports = function(crowi) {
    * Delete Bookmarks, Attachments, Revisions, Pages and emit delete
    */
   pageSchema.statics.completelyDeletePageRecursively = async function(targetPage, user, options = {}) {
-    const pagePath = targetPage.path;
-
     const findOpts = { includeTrashed: true };
 
-    // find descendants (this array does not include GRANT_RESTRICTED)
-    const result = await this.findListWithDescendants(pagePath, user, findOpts);
-    const pages = result.pages;
-    // add targetPage if 'grant' is GRANT_RESTRICTED
-    //  because findListWithDescendants excludes GRANT_RESTRICTED pages
-    if (targetPage.grant === GRANT_RESTRICTED) {
-      pages.push(targetPage);
-    }
+    // find manageable descendants (this array does not include GRANT_RESTRICTED)
+    const pages = await this.findManageableListWithDescendants(targetPage, user, findOpts);
 
     await Promise.all(pages.map((page) => {
       return this.completelyDeletePage(page, user, options);
@@ -1277,14 +1293,8 @@ module.exports = function(crowi) {
     // sanitize path
     newPagePathPrefix = crowi.xss.process(newPagePathPrefix); // eslint-disable-line no-param-reassign
 
-    // find descendants (this array does not include GRANT_RESTRICTED)
-    const result = await this.findListWithDescendants(path, user, options);
-    const pages = result.pages;
-    // add targetPage if 'grant' is GRANT_RESTRICTED
-    //  because findListWithDescendants excludes GRANT_RESTRICTED pages
-    if (targetPage.grant === GRANT_RESTRICTED) {
-      pages.push(targetPage);
-    }
+    // find manageable descendants
+    const pages = await this.findManageableListWithDescendants(targetPage, user, options);
 
     await Promise.all(pages.map((page) => {
       const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);

+ 1 - 1
src/server/models/revision.js

@@ -9,7 +9,7 @@ module.exports = function(crowi) {
 
   const ObjectId = mongoose.Schema.Types.ObjectId;
   const revisionSchema = new mongoose.Schema({
-    path: { type: String, required: true },
+    path: { type: String, required: true, index: true },
     body: {
       type: String,
       required: true,

+ 38 - 0
src/server/models/share-link.js

@@ -0,0 +1,38 @@
+// disable no-return-await for model functions
+/* eslint-disable no-return-await */
+
+const mongoose = require('mongoose');
+const uniqueValidator = require('mongoose-unique-validator');
+const mongoosePaginate = require('mongoose-paginate-v2');
+
+const ObjectId = mongoose.Schema.Types.ObjectId;
+
+/*
+ * define schema
+ */
+const schema = new mongoose.Schema({
+  relatedPage: {
+    type: ObjectId,
+    ref: 'Page',
+    required: true,
+    index: true,
+  },
+  expiredAt: { type: Date },
+  description: { type: String },
+  createdAt: { type: Date, default: Date.now, required: true },
+});
+schema.plugin(mongoosePaginate);
+schema.plugin(uniqueValidator);
+
+module.exports = function(crowi) {
+
+  schema.methods.isExpired = function() {
+    if (this.expiredAt == null) {
+      return false;
+    }
+    return this.expiredAt.getTime() < new Date().getTime();
+  };
+
+  const model = mongoose.model('ShareLink', schema);
+  return model;
+};

+ 6 - 3
src/server/models/vo/config-pubsub-message.js → src/server/models/vo/s2s-message.js

@@ -1,4 +1,7 @@
-class ConfigPubsubMessage {
+/**
+ * Server-to-server message VO
+ */
+class S2sMessage {
 
   constructor(eventName, body = {}) {
     this.eventName = eventName;
@@ -18,9 +21,9 @@ class ConfigPubsubMessage {
       throw new Error('message body must contain \'eventName\'');
     }
 
-    return new ConfigPubsubMessage(body.eventName, body);
+    return new S2sMessage(body.eventName, body);
   }
 
 }
 
-module.exports = ConfigPubsubMessage;
+module.exports = S2sMessage;

+ 0 - 13
src/server/routes/admin.js

@@ -19,8 +19,6 @@ module.exports = function(crowi, app) {
   const ApiResponse = require('../util/apiResponse');
   const importer = require('../util/importer')(crowi);
 
-  const searchEvent = crowi.event('search');
-
   const MAX_PAGE_LIST = 50;
   const actions = {};
 
@@ -84,17 +82,6 @@ module.exports = function(crowi, app) {
     return pager;
   }
 
-  // setup websocket event for rebuild index
-  searchEvent.on('addPageProgress', (total, current, skip) => {
-    crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip });
-  });
-  searchEvent.on('finishAddPage', (total, current, skip) => {
-    crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip });
-  });
-  searchEvent.on('rebuildingFailed', (error) => {
-    crowi.getIo().sockets.emit('admin:rebuildingFailed', { error: error.message });
-  });
-
   actions.index = function(req, res) {
     return res.render('admin/index');
   };

+ 66 - 17
src/server/routes/apiv3/app-settings.js

@@ -320,6 +320,27 @@ module.exports = (crowi) => {
     await sendMailPromiseWrapper(smtpClient, mailOptions);
   }
 
+  const updateMailSettinConfig = async function(requestMailSettingParams) {
+    const {
+      configManager,
+      mailService,
+    } = crowi;
+
+    // update config without publishing S2sMessage
+    await configManager.updateConfigsInTheSameNamespace('crowi', requestMailSettingParams, true);
+
+    await mailService.initialize();
+    mailService.publishUpdatedMessage();
+
+    return {
+      fromAddress: configManager.getConfig('crowi', 'mail:from'),
+      smtpHost: configManager.getConfig('crowi', 'mail:smtpHost'),
+      smtpPort: configManager.getConfig('crowi', 'mail:smtpPort'),
+      smtpUser: configManager.getConfig('crowi', 'mail:smtpUser'),
+      smtpPassword: configManager.getConfig('crowi', 'mail:smtpPassword'),
+    };
+  };
+
   /**
    * @swagger
    *
@@ -327,7 +348,7 @@ module.exports = (crowi) => {
    *      put:
    *        tags: [AppSettings]
    *        operationId: updateAppSettingMailSetting
-   *        summary: /app-settings/site-url-setting
+   *        summary: /app-settings/mail-setting
    *        description: Update mail setting
    *        requestBody:
    *          required: true
@@ -364,21 +385,7 @@ module.exports = (crowi) => {
     };
 
     try {
-      const { configManager, mailService } = crowi;
-
-      // update config without publishing ConfigPubsubMessage
-      await configManager.updateConfigsInTheSameNamespace('crowi', requestMailSettingParams, true);
-
-      await mailService.initialize();
-      mailService.publishUpdatedMessage();
-
-      const mailSettingParams = {
-        fromAddress: configManager.getConfig('crowi', 'mail:from'),
-        smtpHost: configManager.getConfig('crowi', 'mail:smtpHost'),
-        smtpPort: configManager.getConfig('crowi', 'mail:smtpPort'),
-        smtpUser: configManager.getConfig('crowi', 'mail:smtpUser'),
-        smtpPassword: configManager.getConfig('crowi', 'mail:smtpPassword'),
-      };
+      const mailSettingParams = await updateMailSettinConfig(requestMailSettingParams);
       return res.apiv3({ mailSettingParams });
     }
     catch (err) {
@@ -388,6 +395,48 @@ module.exports = (crowi) => {
     }
   });
 
+  /**
+   * @swagger
+   *
+   *    /app-settings/mail-setting:
+   *      delete:
+   *        tags: [AppSettings]
+   *        operationId: deleteAppSettingMailSetting
+   *        summary: /app-settings/mail-setting
+   *        description: delete mail setting
+   *        requestBody:
+   *          required: true
+   *          content:
+   *            application/json:
+   *              schema:
+   *                $ref: '#/components/schemas/MailSettingParams'
+   *        responses:
+   *          200:
+   *            description: Succeeded to delete mail setting
+   *            content:
+   *              application/json:
+   *                schema:
+   *                  $ref: '#/components/schemas/MailSettingParams'
+   */
+  router.delete('/mail-setting', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
+    const requestMailSettingParams = {
+      'mail:from': null,
+      'mail:smtpHost': null,
+      'mail:smtpPort': null,
+      'mail:smtpUser': null,
+      'mail:smtpPassword': null,
+    };
+    try {
+      const mailSettingParams = await updateMailSettinConfig(requestMailSettingParams);
+      return res.apiv3({ mailSettingParams });
+    }
+    catch (err) {
+      const msg = 'Error occurred in initializing mail setting';
+      logger.error('Error', err);
+      return res.apiv3Err(new ErrorV3(msg, 'initialize-mailSetting-failed'));
+    }
+  });
+
   /**
    * @swagger
    *
@@ -423,7 +472,7 @@ module.exports = (crowi) => {
     try {
       const { configManager, mailService } = crowi;
 
-      // update config without publishing ConfigPubsubMessage
+      // update config without publishing S2sMessage
       await configManager.updateConfigsInTheSameNamespace('crowi', requestAwsSettingParams, true);
 
       await mailService.initialize();

+ 4 - 4
src/server/routes/apiv3/export.js

@@ -43,19 +43,19 @@ module.exports = (crowi) => {
   const adminRequired = require('../../middlewares/admin-required')(crowi);
   const csrf = require('../../middlewares/csrf')(crowi);
 
-  const { exportService } = crowi;
+  const { exportService, socketIoService } = crowi;
 
   this.adminEvent = crowi.event('admin');
 
   // setup event
   this.adminEvent.on('onProgressForExport', (data) => {
-    crowi.getIo().sockets.emit('admin:onProgressForExport', data);
+    socketIoService.getAdminSocket().emit('admin:onProgressForExport', data);
   });
   this.adminEvent.on('onStartZippingForExport', (data) => {
-    crowi.getIo().sockets.emit('admin:onStartZippingForExport', data);
+    socketIoService.getAdminSocket().emit('admin:onStartZippingForExport', data);
   });
   this.adminEvent.on('onTerminateForExport', (data) => {
-    crowi.getIo().sockets.emit('admin:onTerminateForExport', data);
+    socketIoService.getAdminSocket().emit('admin:onTerminateForExport', data);
   });
 
 

+ 4 - 4
src/server/routes/apiv3/import.js

@@ -60,7 +60,7 @@ const generateOverwriteParams = (collectionName, req, options) => {
 };
 
 module.exports = (crowi) => {
-  const { growiBridgeService, importService } = crowi;
+  const { growiBridgeService, importService, socketIoService } = crowi;
   const accessTokenParser = require('../../middlewares/access-token-parser')(crowi);
   const loginRequired = require('../../middlewares/login-required')(crowi);
   const adminRequired = require('../../middlewares/admin-required')(crowi);
@@ -70,13 +70,13 @@ module.exports = (crowi) => {
 
   // setup event
   this.adminEvent.on('onProgressForImport', (data) => {
-    crowi.getIo().sockets.emit('admin:onProgressForImport', data);
+    socketIoService.getAdminSocket().emit('admin:onProgressForImport', data);
   });
   this.adminEvent.on('onTerminateForImport', (data) => {
-    crowi.getIo().sockets.emit('admin:onTerminateForImport', data);
+    socketIoService.getAdminSocket().emit('admin:onTerminateForImport', data);
   });
   this.adminEvent.on('onErrorForImport', (data) => {
-    crowi.getIo().sockets.emit('admin:onErrorForImport', data);
+    socketIoService.getAdminSocket().emit('admin:onErrorForImport', data);
   });
 
   const uploads = multer({

+ 1 - 0
src/server/routes/apiv3/index.js

@@ -39,6 +39,7 @@ module.exports = (crowi) => {
 
   router.use('/page', require('./page')(crowi));
   router.use('/pages', require('./pages')(crowi));
+  router.use('/share-links', require('./share-links')(crowi));
 
   router.use('/bookmarks', require('./bookmarks')(crowi));
 

+ 72 - 1
src/server/routes/apiv3/security-setting.js

@@ -327,7 +327,7 @@ module.exports = (crowi) => {
   async function updateAndReloadStrategySettings(authId, params) {
     const { configManager, passportService } = crowi;
 
-    // update config without publishing ConfigPubsubMessage
+    // update config without publishing S2sMessage
     await configManager.updateConfigsInTheSameNamespace('crowi', params, true);
 
     await passportService.setupStrategyById(authId);
@@ -594,6 +594,77 @@ module.exports = (crowi) => {
     }
   });
 
+
+  /**
+   * @swagger
+   *
+   *    /_api/v3/security-setting/all-share-links:
+   *      get:
+   *        tags: [ShareLinkSettings, apiv3]
+   *        description: Get All ShareLinks at Share Link Setting
+   *        responses:
+   *          200:
+   *            description: all share links
+   *            content:
+   *              application/json:
+   *                schema:
+   *                  properties:
+   *                    securityParams:
+   *                      type: object
+   *                      description: suceed to get all share links
+   */
+  router.get('/all-share-links/', loginRequiredStrictly, adminRequired, async(req, res) => {
+    const ShareLink = crowi.model('ShareLink');
+    const page = parseInt(req.query.page) || 1;
+    const limit = 10;
+    const linkQuery = {};
+    try {
+      const paginateResult = await ShareLink.paginate(
+        linkQuery,
+        {
+          page,
+          limit,
+          populate: {
+            path: 'relatedPage',
+            select: 'path',
+          },
+        },
+      );
+      return res.apiv3({ paginateResult });
+    }
+    catch (err) {
+      const msg = 'Error occured in get share link';
+      logger.error('Error', err);
+      return res.apiv3Err(new ErrorV3(msg, 'get-all-share-links-failed'));
+    }
+  });
+
+  /**
+   * @swagger
+   *
+   *    /_api/v3/security-setting/all-share-links:
+   *      delete:
+   *        tags: [ShareLinkSettings, apiv3]
+   *        description: Delete All ShareLinks at Share Link Setting
+   *        responses:
+   *          200:
+   *            description: succeed to delete all share links
+   */
+
+  router.delete('/all-share-links/', loginRequiredStrictly, adminRequired, async(req, res) => {
+    const ShareLink = crowi.model('ShareLink');
+    try {
+      const removedAct = await ShareLink.remove({});
+      const removeTotal = await removedAct.n;
+      return res.apiv3({ removeTotal });
+    }
+    catch (err) {
+      const msg = 'Error occured in delete all share links';
+      logger.error('Error', err);
+      return res.apiv3Err(new ErrorV3(msg, 'failed-to-delete-all-share-links'));
+    }
+  });
+
   /**
    * @swagger
    *

+ 212 - 0
src/server/routes/apiv3/share-links.js

@@ -0,0 +1,212 @@
+// TODO remove this setting after implemented all
+/* eslint-disable no-unused-vars */
+const loggerFactory = require('@alias/logger');
+
+const logger = loggerFactory('growi:routes:apiv3:share-links');
+
+const express = require('express');
+
+const router = express.Router();
+
+const { body } = require('express-validator/check');
+
+const ErrorV3 = require('../../models/vo/error-apiv3');
+
+const validator = {};
+
+const today = new Date();
+
+/**
+ * @swagger
+ *  tags:
+ *    name: ShareLink
+ */
+
+module.exports = (crowi) => {
+  const loginRequired = require('../../middlewares/login-required')(crowi);
+  const adminRequired = require('../../middlewares/admin-required')(crowi);
+  const csrf = require('../../middlewares/csrf')(crowi);
+  const apiV3FormValidator = require('../../middlewares/apiv3-form-validator')(crowi);
+  const ShareLink = crowi.model('ShareLink');
+
+
+  /**
+   * @swagger
+   *
+   *  paths:
+   *    /share-links/:
+   *      post:
+   *        tags: [ShareLink]
+   *        description: get share links
+   *        parameters:
+   *          - name: relatedPage
+   *            in: query
+   *            required: true
+   *            description: page id of share link
+   *            schema:
+   *              type: string
+   *        responses:
+   *          200:
+   *            description: Succeeded to get share links
+   */
+  router.get('/', loginRequired, async(req, res) => {
+    const { relatedPage } = req.query;
+    try {
+      const shareLinksResult = await ShareLink.find({ relatedPage: { $in: relatedPage } }).populate({ path: 'relatedPage', select: 'path' });
+      return res.apiv3({ shareLinksResult });
+    }
+    catch (err) {
+      const msg = 'Error occurred in get share link';
+      logger.error('Error', err);
+      return res.apiv3Err(new ErrorV3(msg, 'get-shareLink-failed'));
+    }
+  });
+
+  validator.shareLinkStatus = [
+    // validate the page id is null
+    body('relatedPage').not().isEmpty().withMessage('Page Id is null'),
+    // validate expireation date is not empty, is not before today and is date.
+    body('expiredAt').if(value => value != null).isAfter(today.toString()).withMessage('Your Selected date is past'),
+    // validate the length of description is max 100.
+    body('description').isLength({ min: 0, max: 100 }).withMessage('Max length is 100'),
+  ];
+
+  /**
+   * @swagger
+   *
+   *  paths:
+   *    /share-links/:
+   *      post:
+   *        tags: [ShareLink]
+   *        description: Create new share link
+   *        parameters:
+   *          - name: relatedPage
+   *            in: query
+   *            required: true
+   *            description: page id of share link
+   *            schema:
+   *              type: string
+   *          - name: expiredAt
+   *            in: query
+   *            description: expiration date of share link
+   *            schema:
+   *              type: string
+   *          - name: description
+   *            in: query
+   *            description: description of share link
+   *            schema:
+   *              type: string
+   *        responses:
+   *          200:
+   *            description: Succeeded to create one share link
+   */
+
+  router.post('/', loginRequired, csrf, validator.shareLinkStatus, apiV3FormValidator, async(req, res) => {
+    const { relatedPage, expiredAt, description } = req.body;
+    const ShareLink = crowi.model('ShareLink');
+
+    try {
+      const postedShareLink = await ShareLink.create({ relatedPage, expiredAt, description });
+      return res.apiv3(postedShareLink);
+    }
+    catch (err) {
+      const msg = 'Error occured in post share link';
+      logger.error('Error', err);
+      return res.apiv3Err(new ErrorV3(msg, 'post-shareLink-failed'));
+    }
+  });
+
+  /**
+  * @swagger
+  *
+  *    /share-links/:
+  *      delete:
+  *        tags: [ShareLinks]
+  *        summary: /share-links/
+  *        description: delete all share links related one page
+  *        parameters:
+  *          - name: relatedPage
+  *            in: query
+  *            required: true
+  *            description: page id of share link
+  *            schema:
+  *              type: string
+  *        responses:
+  *          200:
+  *            description: Succeeded to delete o all share links related one page
+  */
+  router.delete('/', loginRequired, csrf, async(req, res) => {
+    const { relatedPage } = req.query;
+
+    try {
+      const deletedShareLink = await ShareLink.remove({ relatedPage });
+      return res.apiv3(deletedShareLink);
+    }
+    catch (err) {
+      const msg = 'Error occured in delete share link';
+      logger.error('Error', err);
+      return res.apiv3Err(new ErrorV3(msg, 'delete-shareLink-failed'));
+    }
+  });
+
+  /**
+  * @swagger
+  *
+  *    /share-links/all:
+  *      delete:
+  *        tags: [ShareLinks]
+  *        description: delete all share links
+  *        responses:
+  *          200:
+  *            description: Succeeded to remove all share links
+  */
+  router.delete('/all', loginRequired, adminRequired, csrf, async(req, res) => {
+
+    try {
+      const deletedShareLink = await ShareLink.deleteMany({});
+      const { deletedCount } = deletedShareLink;
+      return res.apiv3({ deletedCount });
+    }
+    catch (err) {
+      const msg = 'Error occurred in delete all share link';
+      logger.error('Error', err);
+      return res.apiv3Err(new ErrorV3(msg, 'delete-all-shareLink-failed'));
+    }
+  });
+
+  /**
+  * @swagger
+  *
+  *    /share-links/{id}:
+  *      delete:
+  *        tags: [ShareLinks]
+  *        description: delete one share link related one page
+  *        parameters:
+  *          - name: id
+  *            in: path
+  *            required: true
+  *            description: id of share link
+  *            schema:
+  *              type: string
+  *        responses:
+  *          200:
+  *            description: Succeeded to delete one share link
+  */
+  router.delete('/:id', loginRequired, csrf, async(req, res) => {
+    const { id } = req.params;
+
+    try {
+      const deletedShareLink = await ShareLink.findOneAndRemove({ _id: id });
+      return res.apiv3({ deletedShareLink });
+    }
+    catch (err) {
+      const msg = 'Error occurred in delete share link';
+      logger.error('Error', err);
+      return res.apiv3Err(new ErrorV3(msg, 'delete-shareLink-failed'));
+    }
+
+  });
+
+
+  return router;
+};

+ 0 - 5
src/server/routes/hackmd.js

@@ -40,11 +40,6 @@ module.exports = function(crowi, app) {
   let agentScriptContentTpl;
   let stylesScriptContentTpl;
 
-  // init 'saveOnHackmd' event
-  pageEvent.on('saveOnHackmd', (page) => {
-    crowi.getIo().sockets.emit('page:editingWithHackmd', { page });
-  });
-
   /**
    * GET /_hackmd/load-agent
    *

+ 7 - 4
src/server/routes/index.js

@@ -10,6 +10,8 @@ module.exports = function(crowi, app) {
   const loginRequiredStrictly = require('../middlewares/login-required')(crowi);
   const loginRequired = require('../middlewares/login-required')(crowi, true);
   const adminRequired = require('../middlewares/admin-required')(crowi);
+  const certifySharedPage = require('../middlewares/certify-shared-page')(crowi);
+  const certifySharedFile = require('../middlewares/certify-shared-file')(crowi);
   const csrf = require('../middlewares/csrf')(crowi);
 
   const uploads = multer({ dest: `${crowi.tmpDir}uploads` });
@@ -120,7 +122,7 @@ module.exports = function(crowi, app) {
 
   app.get('/:id([0-9a-z]{24})'       , loginRequired , page.redirector);
   app.get('/_r/:id([0-9a-z]{24})'    , loginRequired , page.redirector); // alias
-  app.get('/attachment/:id([0-9a-z]{24})'  , loginRequired, attachment.api.get);
+  app.get('/attachment/:id([0-9a-z]{24})' , certifySharedFile , loginRequired, attachment.api.get);
   app.get('/attachment/profile/:id([0-9a-z]{24})' , loginRequired, attachment.api.get);
   app.get('/attachment/:pageId/:fileName', loginRequired, attachment.api.obsoletedGetForMongoDB); // DEPRECATED: remains for backward compatibility for v3.3.x or below
   app.get('/download/:id([0-9a-z]{24})'    , loginRequired, attachment.api.download);
@@ -164,9 +166,8 @@ module.exports = function(crowi, app) {
   app.post('/_api/attachments.removeProfileImage'   , accessTokenParser , loginRequiredStrictly , csrf, attachment.api.removeProfileImage);
   app.get('/_api/attachments.limit'   , accessTokenParser , loginRequiredStrictly, attachment.api.limit);
 
-  app.get('/_api/revisions.get'       , accessTokenParser , loginRequired , revision.api.get);
-  app.get('/_api/revisions.ids'       , accessTokenParser , loginRequired , revision.api.ids);
-  app.get('/_api/revisions.list'      , accessTokenParser , loginRequired , revision.api.list);
+  app.get('/_api/revisions.get'       , certifySharedPage , accessTokenParser , loginRequired , revision.api.get);
+  app.get('/_api/revisions.ids'       , certifySharedPage , accessTokenParser , loginRequired , revision.api.ids);
 
   app.get('/trash$'                   , loginRequired , page.trashPageShowWrapper);
   app.get('/trash/$'                  , loginRequired , page.trashPageListShowWrapper);
@@ -178,6 +179,8 @@ module.exports = function(crowi, app) {
   app.post('/_api/hackmd.discard'        , accessTokenParser , loginRequiredStrictly , csrf, hackmd.validateForApi, hackmd.discard);
   app.post('/_api/hackmd.saveOnHackmd'   , accessTokenParser , loginRequiredStrictly , csrf, hackmd.validateForApi, hackmd.saveOnHackmd);
 
+  app.get('/share/:linkId', page.showSharedPage);
+
   app.get('/*/$'                   , loginRequired , page.showPageWithEndOfSlash, page.notFound);
   app.get('/*'                     , loginRequired , page.showPage, page.notFound);
 

+ 56 - 35
src/server/routes/page.js

@@ -142,6 +142,7 @@ module.exports = function(crowi, app) {
   const PageTagRelation = crowi.model('PageTagRelation');
   const UpdatePost = crowi.model('UpdatePost');
   const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
+  const ShareLink = crowi.model('ShareLink');
 
   const ApiResponse = require('../util/apiResponse');
   const getToday = require('../util/getToday');
@@ -149,42 +150,10 @@ module.exports = function(crowi, app) {
   const { slackNotificationService, configManager } = crowi;
   const interceptorManager = crowi.getInterceptorManager();
   const globalNotificationService = crowi.getGlobalNotificationService();
+  const pageService = crowi.pageService;
 
   const actions = {};
 
-  // register page events
-
-  const pageEvent = crowi.event('page');
-  pageEvent.on('create', (page, user, socketClientId) => {
-    page = serializeToObj(page); // eslint-disable-line no-param-reassign
-    crowi.getIo().sockets.emit('page:create', { page, user, socketClientId });
-  });
-  pageEvent.on('update', (page, user, socketClientId) => {
-    page = serializeToObj(page); // eslint-disable-line no-param-reassign
-    crowi.getIo().sockets.emit('page:update', { page, user, socketClientId });
-  });
-  pageEvent.on('delete', (page, user, socketClientId) => {
-    page = serializeToObj(page); // eslint-disable-line no-param-reassign
-    crowi.getIo().sockets.emit('page:delete', { page, user, socketClientId });
-  });
-
-
-  function serializeToObj(page) {
-    const returnObj = page.toObject();
-    if (page.revisionHackmdSynced != null && page.revisionHackmdSynced._id != null) {
-      returnObj.revisionHackmdSynced = page.revisionHackmdSynced._id;
-    }
-
-    if (page.lastUpdateUser != null && page.lastUpdateUser instanceof User) {
-      returnObj.lastUpdateUser = page.lastUpdateUser.toObject();
-    }
-    if (page.creator != null && page.creator instanceof User) {
-      returnObj.creator = page.creator.toObject();
-    }
-
-    return returnObj;
-  }
-
   function getPathFromRequest(req) {
     return pathUtils.normalizePath(req.params[0] || '');
   }
@@ -349,6 +318,9 @@ module.exports = function(crowi, app) {
     addRendarVarsForPage(renderVars, portalPage);
     await addRenderVarsForSlack(renderVars, portalPage);
 
+    const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: portalPage._id });
+    renderVars.sharelinksNumber = sharelinksNumber;
+
     const limit = 50;
     const offset = parseInt(req.query.offset) || 0;
 
@@ -393,6 +365,9 @@ module.exports = function(crowi, app) {
     await addRenderVarsForSlack(renderVars, page);
     await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
 
+    const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: page._id });
+    renderVars.sharelinksNumber = sharelinksNumber;
+
     if (isUserPage(page.path)) {
       // change template
       view = `layout-${layoutName}/user_page`;
@@ -438,6 +413,52 @@ module.exports = function(crowi, app) {
     return showPageForGrowiBehavior(req, res, next);
   };
 
+  actions.showSharedPage = async function(req, res, next) {
+    const { linkId } = req.params;
+    const revisionId = req.query.revision;
+
+    const layoutName = configManager.getConfig('crowi', 'customize:layout');
+    const view = `layout-${layoutName}/shared_page`;
+
+    const shareLink = await ShareLink.findOne({ _id: linkId }).populate('relatedPage');
+
+    if (shareLink == null || shareLink.relatedPage == null) {
+      // page or sharelink are not found
+      return res.render(`layout-${layoutName}/not_found_shared_page`);
+    }
+
+    let page = shareLink.relatedPage;
+
+    // check if share link is expired
+    if (shareLink.isExpired()) {
+      // page is not found
+      return res.render(`layout-${layoutName}/expired_shared_page`);
+    }
+
+    const renderVars = {};
+
+    renderVars.sharelink = shareLink;
+
+    // presentation mode
+    if (req.query.presentation) {
+      page = await page.populateDataToMakePresentation(revisionId);
+
+      // populate
+      addRendarVarsForPage(renderVars, page);
+      return res.render('page_presentation', renderVars);
+    }
+
+    page.initLatestRevisionField(revisionId);
+
+    // populate
+    page = await page.populateDataToShowRevision();
+    addRendarVarsForPage(renderVars, page);
+    addRendarVarsForScope(renderVars, page);
+
+    await interceptorManager.process('beforeRenderPage', req, res, renderVars);
+    return res.render(view, renderVars);
+  };
+
   /**
    * switch action by behaviorType
    */
@@ -742,7 +763,7 @@ module.exports = function(crowi, app) {
       savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
     }
 
-    const result = { page: serializeToObj(createdPage), tags: savedTags };
+    const result = { page: pageService.serializeToObj(createdPage), tags: savedTags };
     res.json(ApiResponse.success(result));
 
     // update scopes for descendants
@@ -871,7 +892,7 @@ module.exports = function(crowi, app) {
       savedTags = await PageTagRelation.listTagNamesByPage(pageId);
     }
 
-    const result = { page: serializeToObj(page), tags: savedTags };
+    const result = { page: pageService.serializeToObj(page), tags: savedTags };
     res.json(ApiResponse.success(result));
 
     // update scopes for descendants

+ 18 - 93
src/server/routes/revision.js

@@ -45,7 +45,6 @@
  */
 
 module.exports = function(crowi, app) {
-  const debug = require('debug')('growi:routes:revision');
   const logger = require('@alias/logger')('growi:routes:revision');
   const Page = crowi.model('Page');
   const Revision = crowi.model('Revision');
@@ -102,14 +101,14 @@ module.exports = function(crowi, app) {
   actions.api.get = async function(req, res) {
     const pageId = req.query.page_id;
     const revisionId = req.query.revision_id;
+    const { isSharedPage } = req;
 
     if (!pageId || !revisionId) {
       return res.json(ApiResponse.error('Parameter page_id and revision_id are required.'));
     }
 
     // check whether accessible
-    const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
-    if (!isAccessible) {
+    if (!isSharedPage && !(await Page.isAccessiblePageByViewer(pageId, req.user))) {
       return res.json(ApiResponse.error('Current user is not accessible to this page.'));
     }
 
@@ -163,101 +162,27 @@ module.exports = function(crowi, app) {
    *
    * @apiParam {String} page_id      Page Id.
    */
-  actions.api.ids = function(req, res) {
-    const pageId = req.query.page_id || null;
+  actions.api.ids = async function(req, res) {
+    const pageId = req.query.page_id;
+    const { isSharedPage } = req;
 
-    if (pageId && crowi.isPageId(pageId)) {
-      Page.findByIdAndViewer(pageId, req.user)
-        .then((pageData) => {
-          debug('Page found', pageData._id, pageData.path);
-          return Revision.findRevisionList(pageData.path);
-        })
-        .then((revisions) => {
-          return res.json(ApiResponse.success({ revisions }));
-        })
-        .catch((err) => {
-          return res.json(ApiResponse.error(err));
-        });
-    }
-    else {
-      return res.json(ApiResponse.error('Parameter error.'));
+    if (pageId == null) {
+      return res.json(ApiResponse.error('Parameter page_id is required.'));
     }
-  };
-
-  /**
-   * @swagger
-   *
-   *    /revisions.list:
-   *      get:
-   *        tags: [Revisions, CrowiCompatibles]
-   *        operationId: revisions.list
-   *        summary: /revisions.list
-   *        description: Get revisions
-   *        parameters:
-   *          - in: query
-   *            name: page_id
-   *            schema:
-   *              $ref: '#/components/schemas/Page/properties/_id'
-   *          - in: query
-   *            name: revision_ids
-   *            schema:
-   *              type: string
-   *              description: revision ids
-   *              example: 5e0734e472560e001761fa68,5e079a0a0afa6700170a75fb
-   *        responses:
-   *          200:
-   *            description: Succeeded to get revisions.
-   *            content:
-   *              application/json:
-   *                schema:
-   *                  properties:
-   *                    ok:
-   *                      $ref: '#/components/schemas/V1Response/properties/ok'
-   *                    revisions:
-   *                      type: array
-   *                      items:
-   *                        $ref: '#/components/schemas/Revision'
-   *          403:
-   *            $ref: '#/components/responses/403'
-   *          500:
-   *            $ref: '#/components/responses/500'
-   */
-  /**
-   * @api {get} /revisions.list Get revisions
-   * @apiName ListRevision
-   * @apiGroup Revision
-   *
-   * @apiParam {String} revision_ids Revision Ids.
-   * @apiParam {String} page_id      Page Id.
-   */
-  actions.api.list = function(req, res) {
-    const revisionIds = (req.query.revision_ids || '').split(',');
-    const pageId = req.query.page_id || null;
 
-    if (pageId) {
-      Page.findByIdAndViewer(pageId, req.user)
-        .then((pageData) => {
-          debug('Page found', pageData._id, pageData.path);
-          return Revision.findRevisionList(pageData.path, {});
-        })
-        .then((revisions) => {
-          return res.json(ApiResponse.success(revisions));
-        })
-        .catch((err) => {
-          return res.json(ApiResponse.error(err));
-        });
+    // check whether accessible
+    if (!isSharedPage && !(await Page.isAccessiblePageByViewer(pageId, req.user))) {
+      return res.json(ApiResponse.error('Current user is not accessible to this page.'));
     }
-    else if (revisionIds.length > 0) {
-      Revision.findRevisions(revisionIds)
-        .then((revisions) => {
-          return res.json(ApiResponse.success(revisions));
-        })
-        .catch((err) => {
-          return res.json(ApiResponse.error(err));
-        });
+
+    try {
+      const page = await Page.findOne({ _id: pageId });
+      const revisions = await Revision.findRevisionIdList(page.path);
+      return res.json(ApiResponse.success({ revisions }));
     }
-    else {
-      return res.json(ApiResponse.error('Parameter error.'));
+    catch (err) {
+      logger.error('Error revisios.ids', err);
+      return res.json(ApiResponse.error(err));
     }
   };
 

+ 17 - 16
src/server/service/app.js

@@ -2,27 +2,27 @@ const logger = require('@alias/logger')('growi:service:AppService'); // eslint-d
 const { pathUtils } = require('growi-commons');
 
 
-const ConfigPubsubMessage = require('../models/vo/config-pubsub-message');
-const ConfigPubsubMessageHandlable = require('./config-pubsub/handlable');
+const S2sMessage = require('../models/vo/s2s-message');
+const S2sMessageHandlable = require('./s2s-messaging/handlable');
 
 /**
  * the service class of AppService
  */
-class AppService extends ConfigPubsubMessageHandlable {
+class AppService extends S2sMessageHandlable {
 
   constructor(crowi) {
     super();
 
     this.crowi = crowi;
     this.configManager = crowi.configManager;
-    this.configPubsub = crowi.configPubsub;
+    this.s2sMessagingService = crowi.s2sMessagingService;
   }
 
   /**
    * @inheritdoc
    */
-  shouldHandleConfigPubsubMessage(configPubsubMessage) {
-    const { eventName } = configPubsubMessage;
+  shouldHandleS2sMessage(s2sMessage) {
+    const { eventName } = s2sMessage;
     if (eventName !== 'systemInstalled') {
       return false;
     }
@@ -35,10 +35,10 @@ class AppService extends ConfigPubsubMessageHandlable {
   /**
    * @inheritdoc
    */
-  async handleConfigPubsubMessage(configPubsubMessage) {
+  async handleS2sMessage(s2sMessage) {
     logger.info('Invoke post installation process by pubsub notification');
 
-    const { crowi, configManager, configPubsub } = this;
+    const { crowi, configManager, s2sMessagingService } = this;
 
     // load config and setup
     await configManager.loadConfigs();
@@ -48,26 +48,27 @@ class AppService extends ConfigPubsubMessageHandlable {
       crowi.setupAfterInstall();
 
       // remove message handler
-      configPubsub.removeMessageHandler(this);
+      s2sMessagingService.removeMessageHandler(this);
     }
   }
 
   async publishPostInstallationMessage() {
-    const { configPubsub } = this;
+    const { s2sMessagingService } = this;
 
-    if (configPubsub != null) {
-      const configPubsubMessage = new ConfigPubsubMessage('systemInstalled');
+    if (s2sMessagingService != null) {
+      const s2sMessage = new S2sMessage('systemInstalled');
 
       try {
-        await configPubsub.publish(configPubsubMessage);
+        await s2sMessagingService.publish(s2sMessage);
       }
       catch (e) {
-        logger.error('Failed to publish post installation message with configPubsub: ', e.message);
+        logger.error('Failed to publish post installation message with S2sMessagingService: ', e.message);
       }
+
+      // remove message handler
+      s2sMessagingService.removeMessageHandler(this);
     }
 
-    // remove message handler
-    configPubsub.removeMessageHandler(this);
   }
 
   getAppTitle() {

+ 14 - 8
src/server/service/config-loader.js

@@ -107,6 +107,12 @@ const ENV_VAR_NAME_TO_CONFIG_INFO = {
   //   type:    ,
   //   default:
   // },
+  DRAWIO_URI: {
+    ns:      'crowi',
+    key:     'app:drawioUri',
+    type:    TYPES.STRING,
+    default: null,
+  },
   NCHAN_URI: {
     ns:      'crowi',
     key:     'app:nchanUri',
@@ -125,27 +131,27 @@ const ENV_VAR_NAME_TO_CONFIG_INFO = {
     type:    TYPES.BOOLEAN,
     default: false,
   },
-  CONFIG_PUBSUB_SERVER_TYPE: {
+  S2SMSG_PUBSUB_SERVER_TYPE: {
     ns:      'crowi',
-    key:     'configPubsub:serverType',
+    key:     's2sMessagingPubsub:serverType',
     type:    TYPES.STRING,
     default: null,
   },
-  CONFIG_PUBSUB_NCHAN_PUBLISH_PATH: {
+  S2SMSG_PUBSUB_NCHAN_PUBLISH_PATH: {
     ns:      'crowi',
-    key:     'configPubsub:nchan:publishPath',
+    key:     's2sMessagingPubsub:nchan:publishPath',
     type:    TYPES.STRING,
     default: '/pubsub',
   },
-  CONFIG_PUBSUB_NCHAN_SUBSCRIBE_PATH: {
+  S2SMSG_PUBSUB_NCHAN_SUBSCRIBE_PATH: {
     ns:      'crowi',
-    key:     'configPubsub:nchan:subscribePath',
+    key:     's2sMessagingPubsub:nchan:subscribePath',
     type:    TYPES.STRING,
     default: '/pubsub',
   },
-  CONFIG_PUBSUB_NCHAN_CHANNEL_ID: {
+  S2SMSG_PUBSUB_NCHAN_CHANNEL_ID: {
     ns:      'crowi',
-    key:     'configPubsub:nchan:channelId',
+    key:     's2sMessagingPubsub:nchan:channelId',
     type:    TYPES.STRING,
     default: null,
   },

+ 18 - 16
src/server/service/config-manager.js

@@ -1,7 +1,9 @@
 const logger = require('@alias/logger')('growi:service:ConfigManager');
 
-const ConfigPubsubMessage = require('../models/vo/config-pubsub-message');
-const ConfigPubsubMessageHandlable = require('./config-pubsub/handlable');
+const parseISO = require('date-fns/parseISO');
+
+const S2sMessage = require('../models/vo/s2s-message');
+const S2sMessageHandlable = require('./s2s-messaging/handlable');
 
 const ConfigLoader = require('./config-loader');
 
@@ -22,7 +24,7 @@ const KEYS_FOR_SAML_USE_ONLY_ENV_OPTION = [
   'security:passport-saml:ABLCRule',
 ];
 
-class ConfigManager extends ConfigPubsubMessageHandlable {
+class ConfigManager extends S2sMessageHandlable {
 
   constructor(configModel) {
     super();
@@ -50,11 +52,11 @@ class ConfigManager extends ConfigPubsubMessageHandlable {
   }
 
   /**
-   * Set ConfigPubsubDelegator instance
-   * @param {ConfigPubsubDelegator} configPubsub
+   * Set S2sMessagingServiceDelegator instance
+   * @param {S2sMessagingServiceDelegator} s2sMessagingService
    */
-  async setPubsub(configPubsub) {
-    this.configPubsub = configPubsub;
+  async setS2sMessagingService(s2sMessagingService) {
+    this.s2sMessagingService = s2sMessagingService;
   }
 
   /**
@@ -180,7 +182,7 @@ class ConfigManager extends ConfigPubsubMessageHandlable {
    *  );
    * ```
    */
-  async updateConfigsInTheSameNamespace(namespace, configs, withoutPublishingConfigPubsubMessage) {
+  async updateConfigsInTheSameNamespace(namespace, configs, withoutPublishingS2sMessage) {
     const queries = [];
     for (const key of Object.keys(configs)) {
       queries.push({
@@ -196,7 +198,7 @@ class ConfigManager extends ConfigPubsubMessageHandlable {
     await this.loadConfigs();
 
     // publish updated date after reloading
-    if (this.configPubsub != null && !withoutPublishingConfigPubsubMessage) {
+    if (this.s2sMessagingService != null && !withoutPublishingS2sMessage) {
       this.publishUpdateMessage();
     }
   }
@@ -309,32 +311,32 @@ class ConfigManager extends ConfigPubsubMessageHandlable {
   }
 
   async publishUpdateMessage() {
-    const configPubsubMessage = new ConfigPubsubMessage('configUpdated', { updatedAt: new Date() });
+    const s2sMessage = new S2sMessage('configUpdated', { updatedAt: new Date() });
 
     try {
-      await this.configPubsub.publish(configPubsubMessage);
+      await this.s2sMessagingService.publish(s2sMessage);
     }
     catch (e) {
-      logger.error('Failed to publish update message with configPubsub: ', e.message);
+      logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
     }
   }
 
   /**
    * @inheritdoc
    */
-  shouldHandleConfigPubsubMessage(configPubsubMessage) {
-    const { eventName, updatedAt } = configPubsubMessage;
+  shouldHandleS2sMessage(s2sMessage) {
+    const { eventName, updatedAt } = s2sMessage;
     if (eventName !== 'configUpdated' || updatedAt == null) {
       return false;
     }
 
-    return this.lastLoadedAt == null || this.lastLoadedAt < new Date(configPubsubMessage.updatedAt);
+    return this.lastLoadedAt == null || this.lastLoadedAt < parseISO(s2sMessage.updatedAt);
   }
 
   /**
    * @inheritdoc
    */
-  async handleConfigPubsubMessage(configPubsubMessage) {
+  async handleS2sMessage(s2sMessage) {
     logger.info('Reload configs by pubsub notification');
     return this.loadConfigs();
   }

+ 0 - 14
src/server/service/config-pubsub/handlable.js

@@ -1,14 +0,0 @@
-// TODO: make interface with TS
-class ConfigPubsubMessageHandlable {
-
-  shouldHandleConfigPubsubMessage(configPubsubMessage) {
-    throw new Error('implement this');
-  }
-
-  async handleConfigPubsubMessage(configPubsubMessage) {
-    throw new Error('implement this');
-  }
-
-}
-
-module.exports = ConfigPubsubMessageHandlable;

+ 0 - 195
src/server/service/config-pubsub/nchan.js

@@ -1,195 +0,0 @@
-const logger = require('@alias/logger')('growi:service:config-pubsub:nchan');
-
-const path = require('path');
-const axios = require('axios');
-const WebSocketClient = require('websocket').client;
-
-const ConfigPubsubMessage = require('../../models/vo/config-pubsub-message');
-const ConfigPubsubDelegator = require('./base');
-
-
-class NchanDelegator extends ConfigPubsubDelegator {
-
-  constructor(uri, publishPath, subscribePath, channelId) {
-    super(uri);
-
-    this.publishPath = publishPath;
-    this.subscribePath = subscribePath;
-
-    this.channelId = channelId;
-    this.isConnecting = false;
-
-    /**
-     * A list of ConfigPubsubHandler instance
-     */
-    this.handlableList = [];
-
-    this.client = null;
-    this.connection = null;
-  }
-
-  /**
-   * @inheritdoc
-   */
-  shouldResubscribe() {
-    if (this.connection != null && this.connection.connected) {
-      return false;
-    }
-
-    return !this.isConnecting;
-  }
-
-  /**
-   * @inheritdoc
-   */
-  subscribe(forceReconnect = false) {
-    if (forceReconnect) {
-      if (this.connection != null && this.connection.connected) {
-        this.connection.close();
-      }
-    }
-
-    if (this.client != null && this.shouldResubscribe()) {
-      logger.info('The connection to config pubsub server is offline. Try to reconnect...');
-    }
-
-    // init client
-    if (this.client == null) {
-      this.initClient();
-    }
-
-    // connect
-    this.isConnecting = true;
-    const url = this.constructUrl(this.subscribePath).toString();
-    logger.debug(`Subscribe to ${url}`);
-    this.client.connect(url.toString());
-  }
-
-  /**
-   * @inheritdoc
-   */
-  async publish(configPubsubMessage) {
-    await super.publish(configPubsubMessage);
-
-    const url = this.constructUrl(this.publishPath).toString();
-
-    logger.debug('Publish message', configPubsubMessage, `to ${url}`);
-
-    return axios.post(url, JSON.stringify(configPubsubMessage));
-  }
-
-  /**
-   * @inheritdoc
-   */
-  addMessageHandler(handlable) {
-    super.addMessageHandler(handlable);
-    this.registerMessageHandlerToConnection(handlable);
-  }
-
-  /**
-   * @inheritdoc
-   */
-  removeMessageHandler(handlable) {
-    super.removeMessageHandler(handlable);
-    this.subscribe(true);
-  }
-
-  registerMessageHandlerToConnection(handlable) {
-    if (this.connection != null) {
-      this.connection.on('message', (messageObj) => {
-        this.handleMessage(messageObj, handlable);
-      });
-    }
-  }
-
-  constructUrl(basepath) {
-    const pathname = this.channelId == null
-      ? basepath //                                 /pubsub
-      : path.join(basepath, this.channelId); //     /pubsub/my-channel-id
-
-    return new URL(pathname, this.uri);
-  }
-
-  initClient() {
-    const client = new WebSocketClient();
-
-    client.on('connectFailed', (error) => {
-      logger.warn(`Connect Error: ${error.toString()}`);
-      this.isConnecting = false;
-    });
-
-    client.on('connect', (connection) => {
-      this.isConnecting = false;
-      this.connection = connection;
-
-      logger.info('WebSocket client connected');
-
-      connection.on('error', (error) => {
-        this.isConnecting = false;
-        logger.error(`Connection Error: ${error.toString()}`);
-      });
-      connection.on('close', () => {
-        logger.info('WebSocket connection closed');
-      });
-
-      // register all message handlers
-      this.handlableList.forEach(handler => this.registerMessageHandlerToConnection(handler));
-    });
-
-    this.client = client;
-  }
-
-  /**
-   * Handle message string with the specified ConfigPubsubHandler
-   *
-   * @see https://github.com/theturtle32/WebSocket-Node/blob/1f7ffba2f7a6f9473bcb39228264380ce2772ba7/docs/WebSocketConnection.md#message
-   *
-   * @param {object} message WebSocket-Node message object
-   * @param {ConfigPubsubHandler} handlable
-   */
-  handleMessage(message, handlable) {
-    if (message.type !== 'utf8') {
-      logger.warn('Only utf8 message is supported.');
-    }
-
-    try {
-      const configPubsubMessage = ConfigPubsubMessage.parse(message.utf8Data);
-
-      // check uid
-      if (configPubsubMessage.publisherUid === this.uid) {
-        logger.debug(`Skip processing by ${handlable.constructor.name} because this message is sent by the publisher itself:`, `from ${this.uid}`);
-        return;
-      }
-
-      // check shouldHandleConfigPubsubMessage
-      const shouldHandle = handlable.shouldHandleConfigPubsubMessage(configPubsubMessage);
-      logger.debug(`${handlable.constructor.name}.shouldHandleConfigPubsubMessage(`, configPubsubMessage, `) => ${shouldHandle}`);
-
-      if (shouldHandle) {
-        handlable.handleConfigPubsubMessage(configPubsubMessage);
-      }
-    }
-    catch (err) {
-      logger.warn('Could not handle a message: ', err.message);
-    }
-  }
-
-}
-
-module.exports = function(crowi) {
-  const { configManager } = crowi;
-
-  const uri = configManager.getConfig('crowi', 'app:nchanUri');
-
-  // when nachan server URI is not set
-  if (uri == null) {
-    logger.warn('NCHAN_URI is not specified.');
-    return;
-  }
-
-  const publishPath = configManager.getConfig('crowi', 'configPubsub:nchan:publishPath');
-  const subscribePath = configManager.getConfig('crowi', 'configPubsub:nchan:subscribePath');
-  const channelId = configManager.getConfig('crowi', 'configPubsub:nchan:channelId');
-
-  return new NchanDelegator(uri, publishPath, subscribePath, channelId);
-};

+ 13 - 13
src/server/service/customize.js

@@ -3,20 +3,20 @@ const logger = require('@alias/logger')('growi:service:CustomizeService');
 
 const DevidedPagePath = require('@commons/models/devided-page-path');
 
-const ConfigPubsubMessage = require('../models/vo/config-pubsub-message');
-const ConfigPubsubMessageHandlable = require('./config-pubsub/handlable');
+const S2sMessage = require('../models/vo/s2s-message');
+const S2sMessageHandlable = require('./s2s-messaging/handlable');
 
 
 /**
  * the service class of CustomizeService
  */
-class CustomizeService extends ConfigPubsubMessageHandlable {
+class CustomizeService extends S2sMessageHandlable {
 
   constructor(crowi) {
     super();
 
     this.configManager = crowi.configManager;
-    this.configPubsub = crowi.configPubsub;
+    this.s2sMessagingService = crowi.s2sMessagingService;
     this.appService = crowi.appService;
     this.xssService = crowi.xssService;
 
@@ -26,19 +26,19 @@ class CustomizeService extends ConfigPubsubMessageHandlable {
   /**
    * @inheritdoc
    */
-  shouldHandleConfigPubsubMessage(configPubsubMessage) {
-    const { eventName, updatedAt } = configPubsubMessage;
+  shouldHandleS2sMessage(s2sMessage) {
+    const { eventName, updatedAt } = s2sMessage;
     if (eventName !== 'customizeServiceUpdated' || updatedAt == null) {
       return false;
     }
 
-    return this.lastLoadedAt == null || this.lastLoadedAt < new Date(configPubsubMessage.updatedAt);
+    return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
   }
 
   /**
    * @inheritdoc
    */
-  async handleConfigPubsubMessage(configPubsubMessage) {
+  async handleS2sMessage(s2sMessage) {
     const { configManager } = this;
 
     logger.info('Reset customized value by pubsub notification');
@@ -48,16 +48,16 @@ class CustomizeService extends ConfigPubsubMessageHandlable {
   }
 
   async publishUpdatedMessage() {
-    const { configPubsub } = this;
+    const { s2sMessagingService } = this;
 
-    if (configPubsub != null) {
-      const configPubsubMessage = new ConfigPubsubMessage('customizeServiceUpdated', { updatedAt: new Date() });
+    if (s2sMessagingService != null) {
+      const s2sMessage = new S2sMessage('customizeServiceUpdated', { updatedAt: new Date() });
 
       try {
-        await configPubsub.publish(configPubsubMessage);
+        await s2sMessagingService.publish(s2sMessage);
       }
       catch (e) {
-        logger.error('Failed to publish update message with configPubsub: ', e.message);
+        logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
       }
     }
   }

+ 13 - 13
src/server/service/mail.js

@@ -4,18 +4,18 @@ const nodemailer = require('nodemailer');
 const swig = require('swig-templates');
 
 
-const ConfigPubsubMessage = require('../models/vo/config-pubsub-message');
-const ConfigPubsubMessageHandlable = require('./config-pubsub/handlable');
+const S2sMessage = require('../models/vo/s2s-message');
+const S2sMessageHandlable = require('./s2s-messaging/handlable');
 
 
-class MailService extends ConfigPubsubMessageHandlable {
+class MailService extends S2sMessageHandlable {
 
   constructor(crowi) {
     super();
 
     this.appService = crowi.appService;
     this.configManager = crowi.configManager;
-    this.configPubsub = crowi.configPubsub;
+    this.s2sMessagingService = crowi.s2sMessagingService;
 
     this.mailConfig = {};
     this.mailer = {};
@@ -26,19 +26,19 @@ class MailService extends ConfigPubsubMessageHandlable {
   /**
    * @inheritdoc
    */
-  shouldHandleConfigPubsubMessage(configPubsubMessage) {
-    const { eventName, updatedAt } = configPubsubMessage;
+  shouldHandleS2sMessage(s2sMessage) {
+    const { eventName, updatedAt } = s2sMessage;
     if (eventName !== 'mailServiceUpdated' || updatedAt == null) {
       return false;
     }
 
-    return this.lastLoadedAt == null || this.lastLoadedAt < new Date(configPubsubMessage.updatedAt);
+    return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
   }
 
   /**
    * @inheritdoc
    */
-  async handleConfigPubsubMessage(configPubsubMessage) {
+  async handleS2sMessage(s2sMessage) {
     const { configManager } = this;
 
     logger.info('Initialize mail settings by pubsub notification');
@@ -47,16 +47,16 @@ class MailService extends ConfigPubsubMessageHandlable {
   }
 
   async publishUpdatedMessage() {
-    const { configPubsub } = this;
+    const { s2sMessagingService } = this;
 
-    if (configPubsub != null) {
-      const configPubsubMessage = new ConfigPubsubMessage('mailServiceUpdated', { updatedAt: new Date() });
+    if (s2sMessagingService != null) {
+      const s2sMessage = new S2sMessage('mailServiceUpdated', { updatedAt: new Date() });
 
       try {
-        await configPubsub.publish(configPubsubMessage);
+        await s2sMessagingService.publish(s2sMessage);
       }
       catch (e) {
-        logger.error('Failed to publish update message with configPubsub: ', e.message);
+        logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
       }
     }
   }

+ 29 - 0
src/server/service/page.js

@@ -0,0 +1,29 @@
+class PageService {
+
+  constructor(crowi) {
+    this.crowi = crowi;
+  }
+
+  serializeToObj(page) {
+    const { User } = this.crowi.models;
+
+    const returnObj = page.toObject();
+
+    // set the ObjectID to revisionHackmdSynced
+    if (page.revisionHackmdSynced != null && page.revisionHackmdSynced._id != null) {
+      returnObj.revisionHackmdSynced = page.revisionHackmdSynced._id;
+    }
+
+    if (page.lastUpdateUser != null && page.lastUpdateUser instanceof User) {
+      returnObj.lastUpdateUser = page.lastUpdateUser.toObject();
+    }
+    if (page.creator != null && page.creator instanceof User) {
+      returnObj.creator = page.creator.toObject();
+    }
+
+    return returnObj;
+  }
+
+}
+
+module.exports = PageService;

+ 13 - 13
src/server/service/passport.js

@@ -13,13 +13,13 @@ const SamlStrategy = require('passport-saml').Strategy;
 const OIDCIssuer = require('openid-client').Issuer;
 const BasicStrategy = require('passport-http').BasicStrategy;
 
-const ConfigPubsubMessage = require('../models/vo/config-pubsub-message');
-const ConfigPubsubMessageHandlable = require('./config-pubsub/handlable');
+const S2sMessage = require('../models/vo/s2s-message');
+const S2sMessageHandlable = require('./s2s-messaging/handlable');
 
 /**
  * the service class of Passport
  */
-class PassportService extends ConfigPubsubMessageHandlable {
+class PassportService extends S2sMessageHandlable {
 
   // see '/lib/form/login.js'
   static get USERNAME_FIELD() { return 'loginForm[username]' }
@@ -129,21 +129,21 @@ class PassportService extends ConfigPubsubMessageHandlable {
   /**
    * @inheritdoc
    */
-  shouldHandleConfigPubsubMessage(configPubsubMessage) {
-    const { eventName, updatedAt, strategyId } = configPubsubMessage;
+  shouldHandleS2sMessage(s2sMessage) {
+    const { eventName, updatedAt, strategyId } = s2sMessage;
     if (eventName !== 'passportServiceUpdated' || updatedAt == null || strategyId == null) {
       return false;
     }
 
-    return this.lastLoadedAt == null || this.lastLoadedAt < new Date(configPubsubMessage.updatedAt);
+    return this.lastLoadedAt == null || this.lastLoadedAt < new Date(s2sMessage.updatedAt);
   }
 
   /**
    * @inheritdoc
    */
-  async handleConfigPubsubMessage(configPubsubMessage) {
+  async handleS2sMessage(s2sMessage) {
     const { configManager } = this.crowi;
-    const { strategyId } = configPubsubMessage;
+    const { strategyId } = s2sMessage;
 
     logger.info('Reset strategy by pubsub notification');
     await configManager.loadConfigs();
@@ -151,19 +151,19 @@ class PassportService extends ConfigPubsubMessageHandlable {
   }
 
   async publishUpdatedMessage(strategyId) {
-    const { configPubsub } = this.crowi;
+    const { s2sMessagingService } = this.crowi;
 
-    if (configPubsub != null) {
-      const configPubsubMessage = new ConfigPubsubMessage('passportStrategyReloaded', {
+    if (s2sMessagingService != null) {
+      const s2sMessage = new S2sMessage('passportStrategyReloaded', {
         updatedAt: new Date(),
         strategyId,
       });
 
       try {
-        await configPubsub.publish(configPubsubMessage);
+        await s2sMessagingService.publish(s2sMessage);
       }
       catch (e) {
-        logger.error('Failed to publish update message with configPubsub: ', e.message);
+        logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
       }
     }
   }

Некоторые файлы не были показаны из-за большого количества измененных файлов