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

Merge pull request #4425 from weseek/feat/77830-save-subscriptioin-model

Feat: save subscription model
Shun Miyazawa 4 лет назад
Родитель
Сommit
94884e88b4

+ 2 - 2
packages/app/src/components/Navbar/SubNavButtons.jsx

@@ -7,7 +7,7 @@ import { withUnstatedContainers } from '../UnstatedUtils';
 
 import BookmarkButton from '../BookmarkButton';
 import LikeButton from '../LikeButton';
-import WatchButton from '../WatchButton';
+import SubscribeButton from '../SubscribeButton';
 import PageManagement from '../Page/PageManagement';
 
 const SubnavButtons = (props) => {
@@ -23,7 +23,7 @@ const SubnavButtons = (props) => {
     return (
       <>
         <span>
-          <WatchButton />
+          <SubscribeButton pageId={pageContainer.state.pageId} />
         </span>
         {pageContainer.isAbleToShowLikeButton && (
           <span>

+ 64 - 0
packages/app/src/components/SubscribeButton.tsx

@@ -0,0 +1,64 @@
+import React, { useState, FC } from 'react';
+
+import { useTranslation } from 'react-i18next';
+import { UncontrolledTooltip } from 'reactstrap';
+import { withUnstatedContainers } from './UnstatedUtils';
+
+import { toastError } from '~/client/util/apiNotification';
+import AppContainer from '~/client/services/AppContainer';
+import PageContainer from '~/client/services/PageContainer';
+
+type Props = {
+  appContainer: AppContainer,
+  pageId: string,
+};
+
+const SubscruibeButton: FC<Props> = (props: Props) => {
+  const { t } = useTranslation();
+
+  const { appContainer, pageId } = props;
+  const [isSubscribing, setIsSubscribing] = useState(false);
+
+  const handleClick = async() => {
+    if (appContainer.isGuestUser) {
+      return;
+    }
+
+    try {
+      const res = await appContainer.apiv3Put('page/subscribe', { pageId, status: !isSubscribing });
+      if (res) {
+        const { subscription } = res.data;
+        setIsSubscribing(subscription.status === 'SUBSCRIBE');
+      }
+    }
+    catch (err) {
+      toastError(err);
+    }
+  };
+
+  return (
+    <>
+      <button
+        type="button"
+        id="subscribe-button"
+        onClick={handleClick}
+        className={`btn btn-subscribe border-0 ${isSubscribing ? 'active' : ''}  ${appContainer.isGuestUser ? 'disabled' : ''}`}
+      >
+        <i className={isSubscribing ? 'fa fa-eye' : 'fa fa-eye-slash'}></i>
+      </button>
+
+      {appContainer.isGuestUser && (
+        <UncontrolledTooltip placement="top" target="subscribe-button" fade={false}>
+          {t('Not available for guest')}
+        </UncontrolledTooltip>
+      )}
+    </>
+  );
+
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const SubscruibeButtonWrapper = withUnstatedContainers(SubscruibeButton, [AppContainer, PageContainer]);
+export default SubscruibeButtonWrapper;

+ 0 - 45
packages/app/src/components/WatchButton.jsx

@@ -1,45 +0,0 @@
-import React, { useState } from 'react';
-import PropTypes from 'prop-types';
-
-import { withTranslation } from 'react-i18next';
-
-
-const WatchButton = (props) => {
-
-  const [isWatching, setIsWatching] = useState(true);
-
-  const handleClick = () => {
-    setIsWatching(!isWatching);
-  };
-
-  return (
-    <>
-      <button
-        type="button"
-        id="watch-button"
-        onClick={handleClick}
-        className={`btn btn-watch border-0 ${`btn-${props.size}`} ${isWatching ? 'active' : ''} `}
-      >
-        {isWatching && (
-          <i className="fa fa-eye"></i>
-        )}
-
-        {!isWatching && (
-          <i className="fa fa-eye-slash"></i>
-        )}
-      </button>
-
-    </>
-  );
-
-};
-
-WatchButton.propTypes = {
-  size: PropTypes.string,
-};
-
-WatchButton.defaultProps = {
-  size: 'md',
-};
-
-export default withTranslation()(WatchButton);

+ 4 - 4
packages/app/src/server/models/activity.ts

@@ -77,10 +77,10 @@ module.exports = function(crowi: Crowi) {
     const { user: actionUser, targetModel, target } = this;
 
     const model: any = await this.model(targetModel).findById(target);
-    const [targetUsers, watchUsers, ignoreUsers] = await Promise.all([
+    const [targetUsers, subscribeUsers, unsubscribeUsers] = await Promise.all([
       model.getNotificationTargetUsers(),
-      Subscription.getWatchers((target as any) as Types.ObjectId),
-      Subscription.getUnwatchers((target as any) as Types.ObjectId),
+      Subscription.getSubscription((target as any) as Types.ObjectId),
+      Subscription.getUnsubscription((target as any) as Types.ObjectId),
     ]);
 
     const unique = array => Object.values(array.reduce((objects, object) => ({ ...objects, [object.toString()]: object }), {}));
@@ -88,7 +88,7 @@ module.exports = function(crowi: Crowi) {
       const ids = pull.map(object => object.toString());
       return array.filter(object => !ids.includes(object.toString()));
     };
-    const notificationUsers = filter(unique([...targetUsers, ...watchUsers]), [...ignoreUsers, actionUser]);
+    const notificationUsers = filter(unique([...targetUsers, ...subscribeUsers]), [...unsubscribeUsers, actionUser]);
     const activeNotificationUsers = await User.find({
       _id: { $in: notificationUsers },
       status: User.STATUS_ACTIVE,

+ 20 - 28
packages/app/src/server/models/subscription.ts

@@ -5,9 +5,9 @@ import {
 import ActivityDefine from '../util/activityDefine';
 import { getOrCreateModel } from '../util/mongoose-utils';
 
-const STATUS_WATCH = 'WATCH';
-const STATUS_UNWATCH = 'UNWATCH';
-const STATUSES = [STATUS_WATCH, STATUS_UNWATCH];
+export const STATUS_SUBSCRIBE = 'SUBSCRIBE';
+export const STATUS_UNSUBSCRIBE = 'UNSUBSCRIBE';
+const STATUSES = [STATUS_SUBSCRIBE, STATUS_UNSUBSCRIBE];
 
 export interface ISubscription {
   user: Types.ObjectId
@@ -16,18 +16,18 @@ export interface ISubscription {
   status: string
   createdAt: Date
 
-  isWatching(): boolean
-  isUnwatching(): boolean
+  isSubscribing(): boolean
+  isUnsubscribing(): boolean
 }
 
 export interface SubscriptionDocument extends ISubscription, Document {}
 
 export interface SubscriptionModel extends Model<SubscriptionDocument> {
   findByUserIdAndTargetId(userId: Types.ObjectId, targetId: Types.ObjectId): any
-  upsertWatcher(user: Types.ObjectId, targetModel: string, target: Types.ObjectId, status: string): any
-  watchByPageId(user: Types.ObjectId, pageId: Types.ObjectId, status: string): any
-  getWatchers(target: Types.ObjectId): Promise<Types.ObjectId[]>
-  getUnwatchers(target: Types.ObjectId): Promise<Types.ObjectId[]>
+  upsertSubscription(user: Types.ObjectId, targetModel: string, target: Types.ObjectId, status: string): any
+  subscribeByPageId(user: Types.ObjectId, pageId: Types.ObjectId, status: string): any
+  getSubscription(target: Types.ObjectId): Promise<Types.ObjectId[]>
+  getUnsubscription(target: Types.ObjectId): Promise<Types.ObjectId[]>
 }
 
 const subscriptionSchema = new Schema<SubscriptionDocument, SubscriptionModel>({
@@ -55,19 +55,19 @@ const subscriptionSchema = new Schema<SubscriptionDocument, SubscriptionModel>({
   createdAt: { type: Date, default: Date.now },
 });
 
-subscriptionSchema.methods.isWatching = function() {
-  return this.status === STATUS_WATCH;
+subscriptionSchema.methods.isSubscribing = function() {
+  return this.status === STATUS_SUBSCRIBE;
 };
 
-subscriptionSchema.methods.isUnwatching = function() {
-  return this.status === STATUS_UNWATCH;
+subscriptionSchema.methods.isUnsubscribing = function() {
+  return this.status === STATUS_UNSUBSCRIBE;
 };
 
 subscriptionSchema.statics.findByUserIdAndTargetId = function(userId, targetId) {
   return this.findOne({ user: userId, target: targetId });
 };
 
-subscriptionSchema.statics.upsertWatcher = function(user, targetModel, target, status) {
+subscriptionSchema.statics.upsertSubscription = function(user, targetModel, target, status) {
   const query = { user, targetModel, target };
   const doc = { ...query, status };
   const options = {
@@ -76,24 +76,16 @@ subscriptionSchema.statics.upsertWatcher = function(user, targetModel, target, s
   return this.findOneAndUpdate(query, doc, options);
 };
 
-subscriptionSchema.statics.watchByPageId = function(user, pageId, status) {
-  return this.upsertWatcher(user, 'Page', pageId, status);
+subscriptionSchema.statics.subscribeByPageId = function(user, pageId, status) {
+  return this.upsertSubscription(user, 'Page', pageId, status);
 };
 
-subscriptionSchema.statics.getWatchers = async function(target) {
-  return this.find({ target, status: STATUS_WATCH }).distinct('user');
+subscriptionSchema.statics.getSubscription = async function(target) {
+  return this.find({ target, status: STATUS_SUBSCRIBE }).distinct('user');
 };
 
-subscriptionSchema.statics.getUnwatchers = async function(target) {
-  return this.find({ target, status: STATUS_UNWATCH }).distinct('user');
-};
-
-subscriptionSchema.statics.STATUS_WATCH = function() {
-  return STATUS_WATCH;
-};
-
-subscriptionSchema.statics.STATUS_UNWATCH = function() {
-  return STATUS_UNWATCH;
+subscriptionSchema.statics.getUnsubscription = async function(target) {
+  return this.find({ target, status: STATUS_UNSUBSCRIBE }).distinct('user');
 };
 
 export default getOrCreateModel<SubscriptionDocument, SubscriptionModel>('Subscription', subscriptionSchema);

+ 45 - 0
packages/app/src/server/routes/apiv3/page.js

@@ -1,6 +1,7 @@
 import { pagePathUtils } from '@growi/core';
 import loggerFactory from '~/utils/logger';
 
+import Subscription, { STATUS_SUBSCRIBE, STATUS_UNSUBSCRIBE } from '~/server/models/subscription';
 
 const logger = loggerFactory('growi:routes:apiv3:page'); // eslint-disable-line no-unused-vars
 
@@ -161,6 +162,10 @@ module.exports = (crowi) => {
       query('fromPath').isString(),
       query('toPath').isString(),
     ],
+    subscribe: [
+      body('pageId').isString(),
+      body('status').isBoolean(),
+    ],
   };
 
   /**
@@ -463,5 +468,45 @@ module.exports = (crowi) => {
   //   return res.apiv3({ dummy });
   // });
 
+  /**
+   * @swagger
+   *
+   *    /page/subscribe:
+   *      put:
+   *        tags: [Page]
+   *        summary: /page/subscribe
+   *        description: Update subscribe status
+   *        operationId: updateSubscribeStatus
+   *        requestBody:
+   *          content:
+   *            application/json:
+   *              schema:
+   *                properties:
+   *                  pageId:
+   *                    $ref: '#/components/schemas/Page/properties/_id'
+   *        responses:
+   *          200:
+   *            description: Succeeded to update subscribe status.
+   *            content:
+   *              application/json:
+   *                schema:
+   *                  $ref: '#/components/schemas/Page'
+   *          500:
+   *            description: Internal server error.
+   */
+  router.put('/subscribe', accessTokenParser, loginRequiredStrictly, csrf, validator.subscribe, apiV3FormValidator, async(req, res) => {
+    const { pageId } = req.body;
+    const userId = req.user._id;
+    const status = req.body.status ? STATUS_SUBSCRIBE : STATUS_UNSUBSCRIBE;
+    try {
+      const subscription = await Subscription.subscribeByPageId(userId, pageId, status);
+      return res.apiv3({ subscription });
+    }
+    catch (err) {
+      logger.error('Failed to update subscribe status', err);
+      return res.apiv3Err(err, 500);
+    }
+  });
+
   return router;
 };

+ 2 - 2
packages/app/src/styles/_subnav.scss

@@ -38,9 +38,9 @@
     }
   }
 
-  .btn-watch,
   .btn-like,
-  .btn-bookmark {
+  .btn-bookmark,
+  .btn-subscribe {
     height: 40px;
     font-size: 20px;
     border-radius: $border-radius-xl;

+ 1 - 1
packages/app/src/styles/atoms/_buttons.scss

@@ -20,7 +20,7 @@
   }
 }
 
-.btn.btn-watch {
+.btn.btn-subscribe {
   @include button-outline-variant($secondary, $success, rgba(lighten($success, 10%), 0.15), rgba(lighten($success, 10%), 0.5));
   &:not(:disabled):not(.disabled):active,
   &:not(:disabled):not(.disabled).active {