Przeglądaj źródła

Merge branch 'feat/export-n-import-revision-4' into feat/export-n-import-revision-5

mizozobu 6 lat temu
rodzic
commit
e74b2dd55d

+ 2 - 0
resource/locales/en-US/translation.json

@@ -763,9 +763,11 @@
 
   "export_management": {
     "export_as_zip": "Export Data as Zip",
+    "export_collections": "Export Collections",
     "check_all": "Check All",
     "uncheck_all": "Uncheck All",
     "export": "Export",
+    "cancel": "Cancel",
     "file": "File",
     "growi_version": "Growi Version",
     "collections": "Collections",

+ 2 - 0
resource/locales/ja/translation.json

@@ -746,9 +746,11 @@
 
   "export_management": {
     "export_as_zip": "Zipファイルでエクスポート",
+    "export_collections": "コレクションのエクスポート",
     "check_all": "全てにチェックを付ける",
     "uncheck_all": "全てからチェックを外す",
     "export": "エクスポート",
+    "cancel": "キャンセル",
     "file": "ファイル名",
     "growi_version": "Growi バージョン",
     "collections": "コレクション",

+ 42 - 14
src/client/js/components/Admin/Export/ExportPage.jsx

@@ -2,7 +2,7 @@ import React, { Fragment } from 'react';
 import PropTypes from 'prop-types';
 import { withTranslation } from 'react-i18next';
 
-import ExportZipForm from './ExportZipForm';
+import ExportZipFormModal from './ExportZipFormModal';
 import ZipFileTable from './ZipFileTable';
 import { createSubscribedElement } from '../../UnstatedUtils';
 import AppContainer from '../../../services/AppContainer';
@@ -14,21 +14,29 @@ class ExportPage extends React.Component {
     super(props);
 
     this.state = {
+      collections: [],
       zipFileStats: [],
+      isExportModalOpen: false,
     };
 
-    this.addZipFileStat = this.addZipFileStat.bind(this);
-    this.removeZipFileStat = this.removeZipFileStat.bind(this);
+    this.onZipFileStatAdd = this.onZipFileStatAdd.bind(this);
+    this.onZipFileStatRemove = this.onZipFileStatRemove.bind(this);
+    this.openExportModal = this.openExportModal.bind(this);
+    this.closeExportModal = this.closeExportModal.bind(this);
   }
 
   async componentDidMount() {
-    // TODO: use apive.get
-    const { zipFileStats } = await this.props.appContainer.apiGet('/v3/export/status', {});
-    this.setState({ zipFileStats });
+    // TODO: use apiv3.get
+    const [{ collections }, { zipFileStats }] = await Promise.all([
+      this.props.appContainer.apiGet('/v3/mongo/collections', {}),
+      this.props.appContainer.apiGet('/v3/export/status', {}),
+    ]);
     // TODO toastSuccess, toastError
+
+    this.setState({ collections, zipFileStats });
   }
 
-  addZipFileStat(newStat) {
+  onZipFileStatAdd(newStat) {
     this.setState((prevState) => {
       return {
         zipFileStats: [...prevState.zipFileStats, newStat],
@@ -36,7 +44,9 @@ class ExportPage extends React.Component {
     });
   }
 
-  removeZipFileStat(fileName) {
+  async onZipFileStatRemove(fileName) {
+    await this.props.appContainer.apiRequest('delete', `/v3/export/${fileName}`, {});
+
     this.setState((prevState) => {
       return {
         zipFileStats: prevState.zipFileStats.filter(stat => stat.fileName !== fileName),
@@ -44,20 +54,38 @@ class ExportPage extends React.Component {
     });
   }
 
+  openExportModal() {
+    this.setState({ isExportModalOpen: true });
+  }
+
+  closeExportModal() {
+    this.setState({ isExportModalOpen: false });
+  }
+
   render() {
     const { t } = this.props;
 
     return (
       <Fragment>
         <h2>{t('export_management.export_as_zip')}</h2>
-        <ExportZipForm
-          zipFileStats={this.state.zipFileStats}
-          addZipFileStat={this.addZipFileStat}
-        />
-        <ZipFileTable
+        <div className="row my-5">
+          <div className="col-xs-offset-3 col-xs-6">
+            <button type="submit" className="btn btn-sm btn-primary" onClick={this.openExportModal}>{t('export_management.export')}</button>
+          </div>
+        </div>
+        <ExportZipFormModal
+          isOpen={this.state.isExportModalOpen}
+          onClose={this.closeExportModal}
+          collections={this.state.collections}
           zipFileStats={this.state.zipFileStats}
-          removeZipFileStat={this.removeZipFileStat}
+          onZipFileStatAdd={this.onZipFileStatAdd}
         />
+        {this.state.zipFileStats.length > 0 && (
+          <ZipFileTable
+            zipFileStats={this.state.zipFileStats}
+            onZipFileStatRemove={this.onZipFileStatRemove}
+          />
+        )}
       </Fragment>
     );
   }

+ 3 - 17
src/client/js/components/Admin/Export/ExportTableMenu.jsx

@@ -8,20 +8,6 @@ import AppContainer from '../../../services/AppContainer';
 
 class ExportTableMenu extends React.Component {
 
-  constructor(props) {
-    super(props);
-
-    this.deleteZipFile = this.deleteZipFile.bind(this);
-  }
-
-  async deleteZipFile(fileName) {
-    // TODO use appContainer.apiv3.delete
-    await this.props.appContainer.apiRequest('delete', `/v3/export/${fileName}`, {});
-
-    this.props.removeZipFileStat(fileName);
-    // TODO toastSuccess, toastError
-  }
-
   render() {
     const { t } = this.props;
 
@@ -33,11 +19,11 @@ class ExportTableMenu extends React.Component {
         <ul className="dropdown-menu" role="menu">
           <li className="dropdown-header">{t('export_management.export_menu')}</li>
           <li>
-            <a href={`/_api/v3/export/${this.props.fileName}`}>
+            <a href={`/admin/export/${this.props.fileName}`}>
               <i className="icon-cloud-download" /> {t('export_management.download')}
             </a>
           </li>
-          <li onClick={() => this.deleteZipFile(this.props.fileName)}>
+          <li onClick={() => this.props.onZipFileStatRemove(this.props.fileName)}>
             <a>
               <span className="text-danger"><i className="icon-trash" /> {t('export_management.delete')}</span>
             </a>
@@ -53,7 +39,7 @@ ExportTableMenu.propTypes = {
   t: PropTypes.func.isRequired, // i18next
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
   fileName: PropTypes.string.isRequired,
-  removeZipFileStat: PropTypes.func.isRequired,
+  onZipFileStatRemove: PropTypes.func.isRequired,
 };
 
 /**

+ 0 - 125
src/client/js/components/Admin/Export/ExportZipForm.jsx

@@ -1,125 +0,0 @@
-import React from 'react';
-import PropTypes from 'prop-types';
-import { withTranslation } from 'react-i18next';
-
-import { createSubscribedElement } from '../../UnstatedUtils';
-import AppContainer from '../../../services/AppContainer';
-// import { toastSuccess, toastError } from '../../../util/apiNotification';
-
-class ExportZipForm extends React.Component {
-
-  constructor(props) {
-    super(props);
-
-    this.state = {
-      collections: new Set(),
-    };
-
-    this.collections = ['pages', 'revisions'];
-
-    this.toggleCheckbox = this.toggleCheckbox.bind(this);
-    this.checkAll = this.checkAll.bind(this);
-    this.uncheckAll = this.uncheckAll.bind(this);
-    this.export = this.export.bind(this);
-    this.validateForm = this.validateForm.bind(this);
-  }
-
-  toggleCheckbox(e) {
-    const { target } = e;
-    const { name, checked } = target;
-
-    this.setState((prevState) => {
-      const collections = new Set(prevState.collections);
-      if (checked) {
-        collections.add(name);
-      }
-      else {
-        collections.delete(name);
-      }
-
-      return { collections };
-    });
-  }
-
-  checkAll() {
-    this.setState({ collections: new Set(this.collections) });
-  }
-
-  uncheckAll() {
-    this.setState({ collections: new Set() });
-  }
-
-  async export(e) {
-    e.preventDefault();
-
-    // TODO use appContainer.apiv3.post
-    const { zipFileStat } = await this.props.appContainer.apiPost('/v3/export', { collections: Array.from(this.state.collections) });
-    // TODO toastSuccess, toastError
-    this.props.addZipFileStat(zipFileStat);
-  }
-
-  validateForm() {
-    return this.state.collections.size > 0;
-  }
-
-  render() {
-    const { t } = this.props;
-
-    return (
-      <form className="my-5" onSubmit={this.export}>
-        <div className="row">
-          <div className="col-sm-12">
-            <button type="button" className="btn btn-sm btn-default mr-2" onClick={this.checkAll}>
-              <i className="fa fa-check-square-o"></i> {t('export_management.check_all')}
-            </button>
-            <button type="button" className="btn btn-sm btn-default mr-2" onClick={this.uncheckAll}>
-              <i className="fa fa-square-o"></i> {t('export_management.uncheck_all')}
-            </button>
-          </div>
-        </div>
-        <div className="row checkbox checkbox-info my-5">
-          {this.collections.map((collectionName) => {
-          return (
-            <div className="col-md-6 my-1" key={collectionName}>
-              <input
-                type="checkbox"
-                id={collectionName}
-                name={collectionName}
-                className="form-check-input"
-                value={collectionName}
-                checked={this.state.collections.has(collectionName)}
-                onChange={this.toggleCheckbox}
-              />
-              <label className="text-capitalize form-check-label ml-3" htmlFor={collectionName}>
-                {collectionName}
-              </label>
-            </div>
-          );
-        })}
-        </div>
-        <div className="row">
-          <div className="col-sm-12 text-center">
-            <button type="submit" className="btn btn-sm btn-primary" disabled={!this.validateForm()}>{t('export_management.export')}</button>
-          </div>
-        </div>
-      </form>
-    );
-  }
-
-}
-
-ExportZipForm.propTypes = {
-  t: PropTypes.func.isRequired, // i18next
-  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  zipFileStats: PropTypes.arrayOf(PropTypes.object).isRequired,
-  addZipFileStat: PropTypes.func.isRequired,
-};
-
-/**
- * Wrapper component for using unstated
- */
-const ExportZipFormWrapper = (props) => {
-  return createSubscribedElement(ExportZipForm, props, [AppContainer]);
-};
-
-export default withTranslation()(ExportZipFormWrapper);

+ 137 - 0
src/client/js/components/Admin/Export/ExportZipFormModal.jsx

@@ -0,0 +1,137 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
+import Modal from 'react-bootstrap/es/Modal';
+
+import { createSubscribedElement } from '../../UnstatedUtils';
+import AppContainer from '../../../services/AppContainer';
+// import { toastSuccess, toastError } from '../../../util/apiNotification';
+
+class ExportZipFormModal extends React.Component {
+
+  constructor(props) {
+    super(props);
+
+    this.state = {
+      collections: new Set(),
+    };
+
+    this.toggleCheckbox = this.toggleCheckbox.bind(this);
+    this.checkAll = this.checkAll.bind(this);
+    this.uncheckAll = this.uncheckAll.bind(this);
+    this.export = this.export.bind(this);
+    this.validateForm = this.validateForm.bind(this);
+  }
+
+  toggleCheckbox(e) {
+    const { target } = e;
+    const { name, checked } = target;
+
+    this.setState((prevState) => {
+      const collections = new Set(prevState.collections);
+      if (checked) {
+        collections.add(name);
+      }
+      else {
+        collections.delete(name);
+      }
+
+      return { collections };
+    });
+  }
+
+  checkAll() {
+    this.setState({ collections: new Set(this.props.collections) });
+  }
+
+  uncheckAll() {
+    this.setState({ collections: new Set() });
+  }
+
+  async export(e) {
+    e.preventDefault();
+
+    // TODO use appContainer.apiv3.post
+    const { zipFileStat } = await this.props.appContainer.apiPost('/v3/export', { collections: Array.from(this.state.collections) });
+    // TODO toastSuccess, toastError
+    this.props.onZipFileStatAdd(zipFileStat);
+    this.props.onClose();
+  }
+
+  validateForm() {
+    return this.state.collections.size > 0;
+  }
+
+  render() {
+    const { t } = this.props;
+
+    return (
+      <Modal show={this.props.isOpen} onHide={this.props.onClose}>
+        <Modal.Header closeButton>
+          <Modal.Title>{t('export_management.export_collections')}</Modal.Title>
+        </Modal.Header>
+
+        <form onSubmit={this.export}>
+          <Modal.Body>
+            <div className="row">
+              <div className="col-sm-12">
+                <button type="button" className="btn btn-sm btn-default mr-2" onClick={this.checkAll}>
+                  <i className="fa fa-check-square-o"></i> {t('export_management.check_all')}
+                </button>
+                <button type="button" className="btn btn-sm btn-default mr-2" onClick={this.uncheckAll}>
+                  <i className="fa fa-square-o"></i> {t('export_management.uncheck_all')}
+                </button>
+              </div>
+            </div>
+            <div className="checkbox checkbox-info">
+              {this.props.collections.map((collectionName) => {
+                return (
+                  <div className="my-1" key={collectionName}>
+                    <input
+                      type="checkbox"
+                      id={collectionName}
+                      name={collectionName}
+                      className="form-check-input"
+                      value={collectionName}
+                      checked={this.state.collections.has(collectionName)}
+                      onChange={this.toggleCheckbox}
+                    />
+                    <label className="text-capitalize form-check-label ml-3" htmlFor={collectionName}>
+                      {collectionName}
+                    </label>
+                  </div>
+                );
+              })}
+            </div>
+          </Modal.Body>
+
+          <Modal.Footer>
+            <button type="button" className="btn btn-sm btn-default" onClick={this.props.onClose}>{t('export_management.cancel')}</button>
+            <button type="submit" className="btn btn-sm btn-primary" disabled={!this.validateForm()}>{t('export_management.export')}</button>
+          </Modal.Footer>
+        </form>
+      </Modal>
+    );
+  }
+
+}
+
+ExportZipFormModal.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+
+  isOpen: PropTypes.bool.isRequired,
+  onClose: PropTypes.func.isRequired,
+  collections: PropTypes.arrayOf(PropTypes.string).isRequired,
+  zipFileStats: PropTypes.arrayOf(PropTypes.object).isRequired,
+  onZipFileStatAdd: PropTypes.func.isRequired,
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const ExportZipFormModalWrapper = (props) => {
+  return createSubscribedElement(ExportZipFormModal, props, [AppContainer]);
+};
+
+export default withTranslation()(ExportZipFormModalWrapper);

+ 3 - 2
src/client/js/components/Admin/Export/ZipFileTable.jsx

@@ -36,7 +36,7 @@ class ZipFileTable extends React.Component {
                 <td>
                   <ExportTableMenu
                     fileName={fileName}
-                    removeZipFileStat={this.props.removeZipFileStat}
+                    onZipFileStatRemove={this.props.onZipFileStatRemove}
                   />
                 </td>
               </tr>
@@ -52,8 +52,9 @@ class ZipFileTable extends React.Component {
 ZipFileTable.propTypes = {
   t: PropTypes.func.isRequired, // i18next
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+
   zipFileStats: PropTypes.arrayOf(PropTypes.object).isRequired,
-  removeZipFileStat: PropTypes.func.isRequired,
+  onZipFileStatRemove: PropTypes.func.isRequired,
 };
 
 /**

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

@@ -18,6 +18,7 @@ module.exports = function(crowi, app) {
     aclService,
     slackNotificationService,
     customizeService,
+    exportService,
   } = crowi;
 
   const recommendedWhitelist = require('@commons/service/xss/recommended-whitelist');
@@ -874,6 +875,21 @@ module.exports = function(crowi, app) {
     return res.render('admin/export');
   };
 
+  actions.export.download = (req, res) => {
+    // TODO: add express validator
+    const { fileName } = req.params;
+
+    try {
+      const zipFile = exportService.getFile(fileName);
+      return res.download(zipFile);
+    }
+    catch (err) {
+      // TODO: use ApiV3Error
+      logger.error(err);
+      return res.json(ApiResponse.error());
+    }
+  };
+
   actions.api = {};
   actions.api.appSetting = async function(req, res) {
     const form = req.form.settingForm;

+ 1 - 37
src/server/routes/apiv3/export.js

@@ -22,7 +22,7 @@ module.exports = (crowi) => {
    *  /export/status:
    *    get:
    *      tags: [Export]
-   *      description: get mongodb collections names and zip files for them
+   *      description: get properties of zip files for export
    *      produces:
    *        - application/json
    *      responses:
@@ -38,42 +38,6 @@ module.exports = (crowi) => {
     return res.json({ ok: true, zipFileStats });
   });
 
-  /**
-   * @swagger
-   *
-   *  /export/download:
-   *    get:
-   *      tags: [Export]
-   *      description: download a zipped json for multiple collections
-   *      produces:
-   *        - application/json
-   *      parameters:
-   *        - name: fileName
-   *          in: path
-   *          description: file name of zip file
-   *          schema:
-   *            type: string
-   *      responses:
-   *        200:
-   *          description: a zip file
-   *          content:
-   *            application/zip:
-   */
-  router.get('/:fileName', async(req, res) => {
-    // TODO: add express validator
-    const { fileName } = req.params;
-
-    try {
-      const zipFile = exportService.getFile(fileName);
-      return res.download(zipFile);
-    }
-    catch (err) {
-      // TODO: use ApiV3Error
-      logger.error(err);
-      return res.status(500).send({ status: 'ERROR' });
-    }
-  });
-
   /**
    * @swagger
    *

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

@@ -9,6 +9,8 @@ const router = express.Router();
 module.exports = (crowi) => {
   router.use('/healthcheck', require('./healthcheck')(crowi));
 
+  router.use('/mongo', require('./mongo')(crowi));
+
   router.use('/export', require('./export')(crowi));
 
   router.use('/import', require('./import')(crowi));

+ 48 - 0
src/server/routes/apiv3/mongo.js

@@ -0,0 +1,48 @@
+const loggerFactory = require('@alias/logger');
+
+const logger = loggerFactory('growi:routes:apiv3:mongo'); // eslint-disable-line no-unused-vars
+
+const express = require('express');
+
+const router = express.Router();
+
+/**
+ * @swagger
+ *  tags:
+ *    name: Mongo
+ */
+
+module.exports = (crowi) => {
+  /**
+   * @swagger
+   *
+   *  /mongo/collections:
+   *    get:
+   *      tags: [Mongo]
+   *      description: get mongodb collections names
+   *      produces:
+   *        - application/json
+   *      responses:
+   *        200:
+   *          description: list of collections in mongoDB
+   *          content:
+   *            application/json:
+   *              schema:
+   *                properties:
+   *                  collections:
+   *                    type: array
+   *                    items:
+   *                      type: string
+   */
+  router.get('/collections', async(req, res) => {
+    const collections = Object.values(crowi.models).map(model => model.collection.collectionName);
+
+    // TODO: use res.apiv3
+    return res.json({
+      ok: true,
+      collections: [...new Set(collections)], // remove duplicates
+    });
+  });
+
+  return router;
+};

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

@@ -165,6 +165,7 @@ module.exports = function(crowi, app) {
 
   // export management for admin
   app.get('/admin/export' , loginRequired() , adminRequired ,admin.export.index);
+  app.get('/admin/export/:fileName' , loginRequired() , adminRequired ,admin.export.download);
 
   app.get('/me'                       , loginRequired() , me.index);
   app.get('/me/password'              , loginRequired() , me.password);