All files / models activity.js

77.42% Statements 72/93
25% Branches 1/4
65.38% Functions 17/26
77.91% Lines 67/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 24515x     15x 15x 15x 15x 15x     15x                                                                     15x 15x           15x 9x   9x 9x 8x   1x             15x 1x   1x 1x 1x   1x                   15x 3x                 3x               15x                               15x                             15x                         15x                               15x       15x 8x 8x 8x 8x 8x   8x 8x       8x       8x 8x         15x 11x 11x 11x   11x 11x           29x 9x 11x 27x   9x 9x       9x           15x 8x 8x 8x   6x 21x 6x   6x   2x           15x 1x   1x 1x           15x    
module.exports = function(crowi) {
  'use strict'
 
  const debug = require('debug')('crowi:models:activity')
  const mongoose = require('mongoose')
  const ObjectId = mongoose.Schema.Types.ObjectId
  const ActivityDefine = require('../util/activityDefine')()
  const activityEvent = crowi.event('Activity')
 
  // TODO: add revision id
  const activitySchema = new mongoose.Schema({
    user: {
      type: ObjectId,
      ref: 'User',
      index: true,
      require: true,
    },
    targetModel: {
      type: String,
      require: true,
      enum: ActivityDefine.getSupportTargetModelNames(),
    },
    target: {
      type: ObjectId,
      refPath: 'targetModel',
      require: true,
    },
    action: {
      type: String,
      require: true,
      enum: ActivityDefine.getSupportActionNames(),
    },
    event: {
      type: ObjectId,
      refPath: 'eventModel',
    },
    eventModel: {
      type: String,
      enum: ActivityDefine.getSupportEventModelNames(),
    },
    createdAt: {
      type: Date,
      default: Date.now,
    },
  })
  activitySchema.index({ target: 1, action: 1 })
  activitySchema.index({ user: 1, target: 1, action: 1, createdAt: 1 }, { unique: true })
 
  /**
   * @param {object} parameters
   * @return {Promise}
   */
  activitySchema.statics.createByParameters = async function(parameters) {
    const Activity = this
 
    try {
      const activity = await Activity.create(parameters)
      return activity
    } catch (e) {
      throw new Error(e.message)
    }
  }
 
  /**
   * @param {object} parameters
   */
  activitySchema.statics.removeByParameters = async function(parameters) {
    const Activity = this
 
    try {
      const activity = await Activity.findOne(parameters)
      activityEvent.emit('remove', activity)
 
      return await Activity.remove(parameters)
    } catch (e) {
      throw new Error(e.message)
    }
  }
 
  /**
   * @param {Comment} comment
   * @return {Promise}
   */
  activitySchema.statics.createByPageComment = function(comment) {
    const parameters = {
      user: comment.creator,
      targetModel: ActivityDefine.MODEL_PAGE,
      target: comment.page,
      eventModel: ActivityDefine.MODEL_COMMENT,
      event: comment._id,
      action: ActivityDefine.ACTION_COMMENT,
    }
 
    return this.createByParameters(parameters)
  }
 
  /**
   * @param {Page} page
   * @param {User} user
   * @return {Promise}
   */
  activitySchema.statics.createByPageLike = function(page, user) {
    const parameters = {
      user: user._id,
      targetModel: ActivityDefine.MODEL_PAGE,
      target: page,
      action: ActivityDefine.ACTION_LIKE,
    }
 
    return this.createByParameters(parameters)
  }
 
  /**
   * @param {Page} page
   * @param {User} user
   * @return {Promise}
   */
  activitySchema.statics.removeByPageUnlike = function(page, user) {
    const parameters = {
      user: user,
      targetModel: ActivityDefine.MODEL_PAGE,
      target: page,
      action: ActivityDefine.ACTION_LIKE,
    }
 
    return this.removeByParameters(parameters)
  }
 
  /**
   * @param {Page} page
   * @return {Promise}
   */
  activitySchema.statics.removeByPage = async function(page) {
    const Activity = this
    const activities = await Activity.find({ target: page })
    for (const activity of activities) {
      activityEvent.emit('remove', activity)
    }
    return Activity.remove({ target: page })
  }
 
  /**
   * @param {User} user
   * @return {Promise}
   */
  activitySchema.statics.findByUser = function(user) {
    const Activity = this
 
    return new Promise(function(resolve, reject) {
      Activity.find({ user: user })
        .sort({ createdAt: -1 })
        .exec(function(err, notifications) {
          if (err) {
            return reject(err)
          }
 
          return resolve(notifications)
        })
    })
  }
 
  activitySchema.statics.getActionUsersFromActivities = function(activities) {
    return activities.map(({ user }) => user).filter((user, i, self) => self.indexOf(user) === i)
  }
 
  activitySchema.methods.getSameActivities = function() {
    const self = this
    const Activity = self.model('Activity')
    const { target, action } = self
    const query = { target, action }
    const limit = 1000
 
    return new Promise(function(resolve, reject) {
      Activity.find(query)
        .sort({ createdAt: -1 })
        .limit(limit)
        .exec(function(err, activities) {
          Iif (err) {
            reject(err)
          }
 
          debug(activities)
          resolve(activities)
        })
    })
  }
 
  activitySchema.methods.getNotificationTargetUsers = async function() {
    const User = crowi.model('User')
    const Watcher = crowi.model('Watcher')
    const { user: actionUser, targetModel, target } = this
 
    const model = await this.model(targetModel).findById(target)
    const [targetUsers, watchUsers, ignoreUsers] = await Promise.all([
      model.getNotificationTargetUsers(),
      Watcher.getWatchers(target),
      Watcher.getIgnorers(target),
    ])
 
    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([...targetUsers, ...watchUsers]), [...ignoreUsers, actionUser])
    const activeNotificationUsers = await User.find({
      _id: { $in: notificationUsers },
      status: User.STATUS_ACTIVE,
    }).distinct('_id')
    return activeNotificationUsers
  }
 
  /**
   * saved hook
   */
  activitySchema.post('save', async function(savedActivity) {
    const Notification = crowi.model('Notification')
    try {
      const [notificationUsers, sameActivities] = await Promise.all([savedActivity.getNotificationTargetUsers(), savedActivity.getSameActivities()])
 
      const notificationPromises = notificationUsers.map(user => {
        const filteredActivities = sameActivities.filter(({ user: sameActionUser }) => user.toString() !== sameActionUser.toString())
        return Notification.upsertByActivity(user, filteredActivities, savedActivity)
      })
      return Promise.all(notificationPromises)
    } catch (err) {
      debug(err)
    }
  })
 
  // because mongoose's 'remove' hook fired only when remove by a method of Document (not by a Model method)
  // move 'save' hook from mongoose's events to activityEvent if I have a time.
  activityEvent.on('remove', async function(activity) {
    const Notification = crowi.model('Notification')
 
    try {
      await Notification.removeActivity(activity)
    } catch (err) {
      debug(err)
    }
  })
 
  return mongoose.model('Activity', activitySchema)
}