Shun Miyazawa 3 лет назад
Родитель
Сommit
efcf49d96a

+ 0 - 2
packages/app/src/server/crowi/index.js

@@ -16,7 +16,6 @@ import Xss from '~/services/xss';
 import loggerFactory from '~/utils/logger';
 import loggerFactory from '~/utils/logger';
 import { projectRoot } from '~/utils/project-dir-utils';
 import { projectRoot } from '~/utils/project-dir-utils';
 
 
-import Activity from '../models/activity';
 import PageRedirect from '../models/page-redirect';
 import PageRedirect from '../models/page-redirect';
 import Tag from '../models/tag';
 import Tag from '../models/tag';
 import UserGroup from '../models/user-group';
 import UserGroup from '../models/user-group';
@@ -281,7 +280,6 @@ Crowi.prototype.setupModels = async function() {
   allModels = models;
   allModels = models;
 
 
   // include models that independent from crowi
   // include models that independent from crowi
-  allModels.Activity = Activity;
   allModels.Tag = Tag;
   allModels.Tag = Tag;
   allModels.UserGroup = UserGroup;
   allModels.UserGroup = UserGroup;
   allModels.PageRedirect = PageRedirect;
   allModels.PageRedirect = PageRedirect;

+ 108 - 105
packages/app/src/server/models/activity.ts

@@ -11,6 +11,7 @@ import {
 } from '~/interfaces/activity';
 } from '~/interfaces/activity';
 
 
 import loggerFactory from '../../utils/logger';
 import loggerFactory from '../../utils/logger';
+import Crowi from '../crowi';
 
 
 import Subscription from './subscription';
 import Subscription from './subscription';
 
 
@@ -36,116 +37,118 @@ export interface ActivityModel extends Model<ActivityDocument> {
   getActionUsersFromActivities(activities: ActivityDocument[]): any[]
   getActionUsersFromActivities(activities: ActivityDocument[]): any[]
 }
 }
 
 
-const snapshotSchema = new Schema<ISnapshot>({
-  username: { type: String, index: true },
-});
-
-// TODO: add revision id
-const activitySchema = new Schema<ActivityDocument, ActivityModel>({
-  user: {
-    type: Schema.Types.ObjectId,
-    ref: 'User',
-    index: true,
-  },
-  ip: {
-    type: String,
-  },
-  endpoint: {
-    type: String,
-  },
-  targetModel: {
-    type: String,
-    enum: AllSupportedTargetModelType,
-  },
-  target: {
-    type: Schema.Types.ObjectId,
-    refPath: 'targetModel',
-  },
-  eventModel: {
-    type: String,
-    enum: AllSupportedEventModelType,
-  },
-  event: {
-    type: Schema.Types.ObjectId,
-  },
-  action: {
-    type: String,
-    enum: AllSupportedActionType,
-    required: true,
-  },
-  snapshot: snapshotSchema,
-}, {
-  timestamps: {
-    createdAt: true,
-    updatedAt: false,
-  },
-});
-activitySchema.index({ target: 1, action: 1 });
-activitySchema.index({
-  user: 1, target: 1, action: 1, createdAt: 1,
-}, { unique: true });
-activitySchema.plugin(mongoosePaginate);
-
-activitySchema.post('save', function() {
-  logger.debug('activity has been created', this);
-});
-
-activitySchema.methods.getNotificationTargetUsers = async function() {
-  const User = getModelSafely('User') || require('~/server/models/user')();
-  const { user: actionUser, target } = this;
-
-  const [subscribeUsers, unsubscribeUsers] = await Promise.all([
-    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 }), {}));
-  const filter = (array, pull) => {
-    const ids = pull.map(object => object.toString());
-    return array.filter(object => !ids.includes(object.toString()));
+export default (crowi: Crowi): any => {
+  const snapshotSchema = new Schema<ISnapshot>({
+    username: { type: String, index: true },
+  });
+
+  // TODO: add revision id
+  const activitySchema = new Schema<ActivityDocument, ActivityModel>({
+    user: {
+      type: Schema.Types.ObjectId,
+      ref: 'User',
+      index: true,
+    },
+    ip: {
+      type: String,
+    },
+    endpoint: {
+      type: String,
+    },
+    targetModel: {
+      type: String,
+      enum: AllSupportedTargetModelType,
+    },
+    target: {
+      type: Schema.Types.ObjectId,
+      refPath: 'targetModel',
+    },
+    eventModel: {
+      type: String,
+      enum: AllSupportedEventModelType,
+    },
+    event: {
+      type: Schema.Types.ObjectId,
+    },
+    action: {
+      type: String,
+      enum: AllSupportedActionType,
+      required: true,
+    },
+    snapshot: snapshotSchema,
+  }, {
+    timestamps: {
+      createdAt: true,
+      updatedAt: false,
+    },
+  });
+  activitySchema.index({ target: 1, action: 1 });
+  activitySchema.index({
+    user: 1, target: 1, action: 1, createdAt: 1,
+  }, { unique: true });
+  activitySchema.plugin(mongoosePaginate);
+
+  activitySchema.post('save', function() {
+    logger.debug('activity has been created', this);
+  });
+
+  activitySchema.methods.getNotificationTargetUsers = async function() {
+    const User = getModelSafely('User') || require('~/server/models/user')();
+    const { user: actionUser, target } = this;
+
+    const [subscribeUsers, unsubscribeUsers] = await Promise.all([
+      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 }), {}));
+    const filter = (array, pull) => {
+      const ids = pull.map(object => object.toString());
+      return array.filter(object => !ids.includes(object.toString()));
+    };
+    const notificationUsers = filter(unique([...subscribeUsers]), [...unsubscribeUsers, actionUser]);
+    const activeNotificationUsers = await User.find({
+      _id: { $in: notificationUsers },
+      status: User.STATUS_ACTIVE,
+    }).distinct('_id');
+    return activeNotificationUsers;
   };
   };
-  const notificationUsers = filter(unique([...subscribeUsers]), [...unsubscribeUsers, actionUser]);
-  const activeNotificationUsers = await User.find({
-    _id: { $in: notificationUsers },
-    status: User.STATUS_ACTIVE,
-  }).distinct('_id');
-  return activeNotificationUsers;
-};
 
 
-activitySchema.statics.getPaginatedActivity = async function(limit: number, offset: number, query) {
-  const paginateResult = await this.paginate(
-    query,
-    {
-      limit,
-      offset,
-      sort: { createdAt: -1 },
-    },
-  );
-  return paginateResult;
-};
+  activitySchema.statics.getPaginatedActivity = async function(limit: number, offset: number, query) {
+    const paginateResult = await this.paginate(
+      query,
+      {
+        limit,
+        offset,
+        sort: { createdAt: -1 },
+      },
+    );
+    return paginateResult;
+  };
 
 
-activitySchema.statics.findSnapshotUsernamesByUsernameRegexWithTotalCount = async function(
-    q: string, option: { sortOpt: number | string, offset: number, limit: number},
-): Promise<{usernames: string[], totalCount: number}> {
-  const opt = option || {};
-  const sortOpt = opt.sortOpt || 1;
-  const offset = opt.offset || 0;
-  const limit = opt.limit || 10;
+  activitySchema.statics.findSnapshotUsernamesByUsernameRegexWithTotalCount = async function(
+      q: string, option: { sortOpt: number | string, offset: number, limit: number},
+  ): Promise<{usernames: string[], totalCount: number}> {
+    const opt = option || {};
+    const sortOpt = opt.sortOpt || 1;
+    const offset = opt.offset || 0;
+    const limit = opt.limit || 10;
 
 
-  const conditions = { 'snapshot.username': { $regex: q, $options: 'i' } };
+    const conditions = { 'snapshot.username': { $regex: q, $options: 'i' } };
 
 
-  const usernames = await this.aggregate()
-    .skip(0)
-    .limit(10000) // Narrow down the search target
-    .match(conditions)
-    .group({ _id: '$snapshot.username' })
-    .sort({ _id: sortOpt }) // Sort "snapshot.username" in ascending order
-    .skip(offset)
-    .limit(limit);
+    const usernames = await this.aggregate()
+      .skip(0)
+      .limit(10000) // Narrow down the search target
+      .match(conditions)
+      .group({ _id: '$snapshot.username' })
+      .sort({ _id: sortOpt }) // Sort "snapshot.username" in ascending order
+      .skip(offset)
+      .limit(limit);
 
 
-  const totalCount = (await this.find(conditions).distinct('snapshot.username')).length;
+    const totalCount = (await this.find(conditions).distinct('snapshot.username')).length;
 
 
-  return { usernames: usernames.map(r => r._id), totalCount };
-};
+    return { usernames: usernames.map(r => r._id), totalCount };
+  };
 
 
-export default getOrCreateModel<ActivityDocument, ActivityModel>('Activity', activitySchema);
+  return getOrCreateModel<ActivityDocument, ActivityModel>('Activity', activitySchema);
+};

+ 2 - 0
packages/app/src/server/models/index.js

@@ -1,7 +1,9 @@
+import Activity from '~/server/models/activity';
 import Page from '~/server/models/page';
 import Page from '~/server/models/page';
 
 
 module.exports = {
 module.exports = {
   Page,
   Page,
+  Activity,
   // TODO GW-2746 bulk export pages
   // TODO GW-2746 bulk export pages
   // PageArchive: require('./page-archive'),
   // PageArchive: require('./page-archive'),
   PageTagRelation: require('./page-tag-relation'),
   PageTagRelation: require('./page-tag-relation'),

+ 6 - 2
packages/app/src/server/service/activity.ts

@@ -1,8 +1,9 @@
 import { getModelSafely } from '@growi/core';
 import { getModelSafely } from '@growi/core';
+import mongoose from 'mongoose';
 
 
 import { IActivity } from '~/interfaces/activity';
 import { IActivity } from '~/interfaces/activity';
 import { IPage } from '~/interfaces/page';
 import { IPage } from '~/interfaces/page';
-import Activity from '~/server/models/activity';
+import { ActivityModel } from '~/server/models/activity';
 
 
 import loggerFactory from '../../utils/logger';
 import loggerFactory from '../../utils/logger';
 import Crowi from '../crowi';
 import Crowi from '../crowi';
@@ -18,9 +19,12 @@ class ActivityService {
 
 
   activityEvent: any;
   activityEvent: any;
 
 
+  Activity!: ActivityModel;
+
   constructor(crowi: Crowi) {
   constructor(crowi: Crowi) {
     this.crowi = crowi;
     this.crowi = crowi;
     this.activityEvent = crowi.event('activity');
     this.activityEvent = crowi.event('activity');
+    this.Activity = mongoose.model('Activity') as unknown as ActivityModel;
 
 
     this.updateByParameters = this.updateByParameters.bind(this);
     this.updateByParameters = this.updateByParameters.bind(this);
 
 
@@ -56,7 +60,7 @@ class ActivityService {
   };
   };
 
 
   updateByParameters = async function(activityId: string, parameters: ParameterType): Promise<IActivity> {
   updateByParameters = async function(activityId: string, parameters: ParameterType): Promise<IActivity> {
-    const activity = await Activity.findOneAndUpdate({ _id: activityId }, parameters, { new: true }) as unknown as IActivity;
+    const activity = await this.Activity.findOneAndUpdate({ _id: activityId }, parameters, { new: true }) as unknown as IActivity;
 
 
     return activity;
     return activity;
   };
   };