activities.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import async from "async";
  2. import CoreClass from "../core";
  3. let ActivitiesModule;
  4. let DBModule;
  5. let CacheModule;
  6. let UtilsModule;
  7. let IOModule;
  8. class _ActivitiesModule extends CoreClass {
  9. // eslint-disable-next-line require-jsdoc
  10. constructor() {
  11. super("activities");
  12. ActivitiesModule = this;
  13. }
  14. /**
  15. * Initialises the activities module
  16. *
  17. * @returns {Promise} - returns promise (reject, resolve)
  18. */
  19. initialize() {
  20. return new Promise(resolve => {
  21. DBModule = this.moduleManager.modules.db;
  22. CacheModule = this.moduleManager.modules.cache;
  23. UtilsModule = this.moduleManager.modules.utils;
  24. IOModule = this.moduleManager.modules.io;
  25. resolve();
  26. });
  27. }
  28. // TODO: Migrate
  29. /**
  30. * Adds a new activity to the database
  31. *
  32. * @param {object} payload - object that contains the payload
  33. * @param {string} payload.userId - the id of the user who's activity is to be added
  34. * @param {string} payload.type - the type of activity (enum specified in schema)
  35. * @param {object} payload.payload - the details of the activity e.g. an array of songs that were added
  36. * @param {string} payload.payload.message - the main message describing the activity e.g. 50 songs added to playlist 'playlist name'
  37. * @param {string} payload.payload.thumbnail - url to a thumbnail e.g. song album art to be used when display an activity
  38. * @param {string} payload.payload.songId - (optional) if relevant, the id of the song related to the activity
  39. * @param {string} payload.payload.playlistId - (optional) if relevant, the id of the playlist related to the activity
  40. * @param {string} payload.payload.stationId - (optional) if relevant, the id of the station related to the activity
  41. * @returns {Promise} - returns promise (reject, resolve)
  42. */
  43. ADD_ACTIVITY(payload) {
  44. return new Promise((resolve, reject) => {
  45. async.waterfall(
  46. [
  47. next => {
  48. DBModule.runJob("GET_MODEL", { modelName: "activity" }, this)
  49. .then(res => next(null, res))
  50. .catch(next);
  51. },
  52. (ActivityModel, next) => {
  53. const { userId, type } = payload;
  54. const activity = new ActivityModel({
  55. userId,
  56. type,
  57. payload: payload.payload
  58. });
  59. activity.save(next);
  60. },
  61. (activity, next) => {
  62. IOModule.runJob("SOCKETS_FROM_USER", { userId: activity.userId }, this)
  63. .then(res => {
  64. res.sockets.forEach(socket => socket.emit("event:activity.create", activity));
  65. next(null, activity);
  66. })
  67. .catch(next);
  68. },
  69. (activity, next) => {
  70. IOModule.runJob("EMIT_TO_ROOM", {
  71. room: `profile-${activity.userId}-activities`,
  72. args: ["event:activity.create", activity]
  73. });
  74. return next(null, activity);
  75. },
  76. (activity, next) => {
  77. const activitiesToCheckFor = [
  78. "user__toggle_nightmode",
  79. "user__toggle_autoskip_disliked_songs",
  80. "song__like",
  81. "song__unlike",
  82. "song__dislike",
  83. "song__undislike"
  84. ];
  85. CacheModule.runJob("HGET", { table: "recentActivities", key: activity.userId })
  86. .then(recentActivity => {
  87. if (recentActivity) {
  88. const FifteenMinsTimeDifference =
  89. new Date() - new Date(recentActivity.createdAt) < 15 * 60 * 1000;
  90. // check if most recent and the new activity have the same type, if it was in the last 15 mins,
  91. // and if it is within the activitiesToCheckFor array
  92. if (
  93. recentActivity.type === activity.type &&
  94. !!FifteenMinsTimeDifference &&
  95. activitiesToCheckFor.includes(activity.type)
  96. )
  97. return ActivitiesModule.runJob(
  98. "CHECK_FOR_ACTIVITY_SPAM",
  99. { userId: activity.userId, type: activity.type },
  100. this
  101. )
  102. .then(() => next(null, activity))
  103. .catch(next);
  104. return next(null, activity);
  105. }
  106. return next(null, activity);
  107. })
  108. .catch(next);
  109. },
  110. // store most recent activity in cache to be quickly accessible
  111. (activity, next) =>
  112. CacheModule.runJob(
  113. "HSET",
  114. {
  115. table: "recentActivities",
  116. key: activity.userId,
  117. value: { createdAt: activity.createdAt, type: activity.type }
  118. },
  119. this
  120. )
  121. .then(() => next(null))
  122. .catch(next)
  123. ],
  124. async (err, activity) => {
  125. if (err) {
  126. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  127. return reject(new Error(err));
  128. }
  129. return resolve(activity);
  130. }
  131. );
  132. });
  133. }
  134. /**
  135. * Removes any activities of the same type within a 15-minute period to prevent spam
  136. *
  137. * @param {object} payload - object that contains the payload
  138. * @param {string} payload.userId - the id of the user to check for duplicates
  139. * @param {string} payload.type - the type of activity to check for duplicates
  140. * @returns {Promise} - returns promise (reject, resolve)
  141. */
  142. async CHECK_FOR_ACTIVITY_SPAM(payload) {
  143. const activityModel = await DBModule.runJob("GET_MODEL", { modelName: "activity" }, this);
  144. return new Promise((resolve, reject) => {
  145. async.waterfall(
  146. [
  147. // find all activities of this type from the last 15 minutes
  148. next => {
  149. activityModel
  150. .find(
  151. {
  152. userId: payload.userId,
  153. type: payload.type,
  154. hidden: false,
  155. createdAt: {
  156. $gte: new Date(new Date() - 15 * 60 * 1000)
  157. }
  158. },
  159. "_id"
  160. )
  161. .sort({ createdAt: -1 })
  162. .skip(1)
  163. .exec(next);
  164. },
  165. // hide these activities and emit to socket listeners
  166. (activities, next) => {
  167. activities.forEach(activity => {
  168. activityModel.updateOne({ _id: activity._id }, { $set: { hidden: true } }).catch(next);
  169. IOModule.runJob("SOCKETS_FROM_USER", { userId: payload.userId }, this)
  170. .then(res =>
  171. res.sockets.forEach(socket => socket.emit("event:activity.hide", activity._id))
  172. )
  173. .catch(next);
  174. IOModule.runJob("EMIT_TO_ROOM", {
  175. room: `profile-${payload.userId}-activities`,
  176. args: ["event:activity.hide", activity._id]
  177. });
  178. });
  179. return next();
  180. }
  181. ],
  182. async err => {
  183. if (err) {
  184. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  185. return reject(new Error(err));
  186. }
  187. return resolve();
  188. }
  189. );
  190. });
  191. }
  192. }
  193. export default new _ActivitiesModule();