activities.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. import async from "async";
  2. import CoreClass from "../core";
  3. let ActivitiesModule;
  4. let DBModule;
  5. let CacheModule;
  6. let UtilsModule;
  7. let WSModule;
  8. let PlaylistsModule;
  9. class _ActivitiesModule extends CoreClass {
  10. // eslint-disable-next-line require-jsdoc
  11. constructor() {
  12. super("activities");
  13. ActivitiesModule = this;
  14. }
  15. /**
  16. * Initialises the activities module
  17. *
  18. * @returns {Promise} - returns promise (reject, resolve)
  19. */
  20. initialize() {
  21. return new Promise(resolve => {
  22. DBModule = this.moduleManager.modules.db;
  23. CacheModule = this.moduleManager.modules.cache;
  24. UtilsModule = this.moduleManager.modules.utils;
  25. WSModule = this.moduleManager.modules.ws;
  26. PlaylistsModule = this.moduleManager.modules.playlists;
  27. resolve();
  28. });
  29. }
  30. // TODO: Migrate
  31. /**
  32. * Adds a new activity to the database
  33. *
  34. * @param {object} payload - object that contains the payload
  35. * @param {string} payload.userId - the id of the user who's activity is to be added
  36. * @param {string} payload.type - the type of activity (enum specified in schema)
  37. * @param {object} payload.payload - the details of the activity e.g. an array of songs that were added
  38. * @param {string} payload.payload.message - the main message describing the activity e.g. 50 songs added to playlist 'playlist name'
  39. * @param {string} payload.payload.thumbnail - url to a thumbnail e.g. song album art to be used when display an activity
  40. * @param {string} payload.payload.songId - (optional) if relevant, the id of the song related to the activity
  41. * @param {string} payload.payload.playlistId - (optional) if relevant, the id of the playlist related to the activity
  42. * @param {string} payload.payload.stationId - (optional) if relevant, the id of the station related to the activity
  43. * @returns {Promise} - returns promise (reject, resolve)
  44. */
  45. ADD_ACTIVITY(payload) {
  46. return new Promise((resolve, reject) => {
  47. async.waterfall(
  48. [
  49. next => {
  50. DBModule.runJob("GET_MODEL", { modelName: "activity" }, this)
  51. .then(res => next(null, res))
  52. .catch(next);
  53. },
  54. (ActivityModel, next) => {
  55. const { userId, type } = payload;
  56. const activity = new ActivityModel({
  57. userId,
  58. type,
  59. payload: payload.payload
  60. });
  61. activity.save(next);
  62. },
  63. (activity, next) => {
  64. WSModule.runJob("SOCKETS_FROM_USER", { userId: activity.userId }, this)
  65. .then(sockets => {
  66. sockets.forEach(socket => socket.dispatch("event:activity.create", activity));
  67. next(null, activity);
  68. })
  69. .catch(next);
  70. },
  71. (activity, next) => {
  72. WSModule.runJob("EMIT_TO_ROOM", {
  73. room: `profile-${activity.userId}-activities`,
  74. args: ["event:activity.create", activity]
  75. });
  76. return next(null, activity);
  77. },
  78. (activity, next) => {
  79. const mergeableActivities = ["playlist__remove_song", "playlist__add_song"];
  80. const spammableActivities = [
  81. "user__toggle_nightmode",
  82. "user__toggle_autoskip_disliked_songs",
  83. "song__like",
  84. "song__unlike",
  85. "song__dislike",
  86. "song__undislike"
  87. ];
  88. CacheModule.runJob("HGET", { table: "recentActivities", key: activity.userId })
  89. .then(recentActivity => {
  90. if (recentActivity) {
  91. const timeDifference = mins =>
  92. new Date() - new Date(recentActivity.createdAt) < mins * 60 * 1000;
  93. // if both activities have the same type, if within last 15 mins and if activity is within the spammableActivities array
  94. if (
  95. recentActivity.type === activity.type &&
  96. !!timeDifference(15) &&
  97. spammableActivities.includes(activity.type)
  98. )
  99. return ActivitiesModule.runJob(
  100. "CHECK_FOR_ACTIVITY_SPAM_TO_HIDE",
  101. { userId: activity.userId, type: activity.type },
  102. this
  103. )
  104. .then(() => next(null, activity))
  105. .catch(next);
  106. // if activity is within the mergeableActivities array, if both activities are about removing/adding and if within last 5 mins
  107. if (
  108. mergeableActivities.includes(activity.type) &&
  109. recentActivity.type === activity.type &&
  110. !!timeDifference(5)
  111. ) {
  112. return PlaylistsModule.runJob("GET_PLAYLIST", {
  113. playlistId: activity.payload.playlistId
  114. })
  115. .then(playlist =>
  116. ActivitiesModule.runJob(
  117. "CHECK_FOR_ACTIVITY_SPAM_TO_MERGE",
  118. {
  119. userId: activity.userId,
  120. type: activity.type,
  121. playlist: {
  122. playlistId: playlist._id,
  123. displayName: playlist.displayName
  124. }
  125. },
  126. this
  127. )
  128. .then(() => next(null, activity))
  129. .catch(next)
  130. )
  131. .catch(next);
  132. }
  133. return next(null, activity);
  134. }
  135. return next(null, activity);
  136. })
  137. .catch(next);
  138. },
  139. // store most recent activity in cache to be quickly accessible
  140. (activity, next) =>
  141. CacheModule.runJob(
  142. "HSET",
  143. {
  144. table: "recentActivities",
  145. key: activity.userId,
  146. value: { createdAt: activity.createdAt, type: activity.type }
  147. },
  148. this
  149. )
  150. .then(() => next(null))
  151. .catch(next)
  152. ],
  153. async (err, activity) => {
  154. if (err) {
  155. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  156. return reject(new Error(err));
  157. }
  158. return resolve(activity);
  159. }
  160. );
  161. });
  162. }
  163. /**
  164. * Merges activities about adding/removing songs from a playlist within a 5-minute period to prevent spam
  165. *
  166. * @param {object} payload - object that contains the payload
  167. * @param {string} payload.userId - the id of the user to check for duplicates
  168. * @param {object} payload.playlist - object that contains info about the relevant playlist
  169. * @param {string} payload.playlist.playlistId - the id of the playlist
  170. * @param {string} payload.playlist.displayName - the display name of the playlist
  171. * @param {string} payload.type - the type of activity to check for duplicates
  172. * @returns {Promise} - returns promise (reject, resolve)
  173. */
  174. async CHECK_FOR_ACTIVITY_SPAM_TO_MERGE(payload) {
  175. const activityModel = await DBModule.runJob("GET_MODEL", { modelName: "activity" }, this);
  176. return new Promise((resolve, reject) => {
  177. async.waterfall(
  178. [
  179. // find all activities of this type from the last 5 minutes
  180. next => {
  181. activityModel
  182. .find(
  183. {
  184. userId: payload.userId,
  185. type: { $in: [payload.type, `${payload.type}s`] },
  186. hidden: false,
  187. createdAt: {
  188. $gte: new Date(new Date() - 5 * 60 * 1000)
  189. },
  190. "payload.playlistId": payload.playlist.playlistId
  191. },
  192. ["_id", "type", "payload.message"]
  193. )
  194. .sort({ createdAt: -1 })
  195. .exec(next);
  196. },
  197. // hide these activities, emit to socket listeners and count number of songs in each
  198. (activities, next) => {
  199. let howManySongs = 0; // how many songs added/removed
  200. activities.forEach(activity => {
  201. activityModel.updateOne({ _id: activity._id }, { $set: { hidden: true } }).catch(next);
  202. WSModule.runJob("SOCKETS_FROM_USER", { userId: payload.userId }, this)
  203. .then(sockets =>
  204. sockets.forEach(socket => socket.dispatch("event:activity.hide", activity._id))
  205. )
  206. .catch(next);
  207. WSModule.runJob("EMIT_TO_ROOM", {
  208. room: `profile-${payload.userId}-activities`,
  209. args: ["event:activity.hide", activity._id]
  210. });
  211. if (activity.type === payload.type) howManySongs += 1;
  212. else if (activity.type === `${payload.type}s`)
  213. howManySongs += parseInt(
  214. activity.payload.message.replace(
  215. /(?:Removed|Added)\s(?<songs>\d+)\ssongs.+/g,
  216. "$<songs>"
  217. )
  218. );
  219. });
  220. return next(null, howManySongs);
  221. },
  222. // // delete in cache the most recent activity to avoid issues when adding a new activity
  223. (howManySongs, next) => {
  224. CacheModule.runJob("HDEL", { table: "recentActivities", key: payload.userId }, this)
  225. .then(() => next(null, howManySongs))
  226. .catch(next);
  227. },
  228. // add a new activity that merges the activities together
  229. (howManySongs, next) => {
  230. const activity = {
  231. userId: payload.userId,
  232. type: "",
  233. payload: {
  234. message: "",
  235. playlistId: payload.playlist.playlistId
  236. }
  237. };
  238. if (payload.type === "playlist__remove_song" || payload.type === "playlist__remove_songs") {
  239. activity.payload.message = `Removed ${howManySongs} songs from playlist <playlistId>${payload.playlist.displayName}</playlistId>`;
  240. activity.type = "playlist__remove_songs";
  241. } else if (payload.type === "playlist__add_song" || payload.type === "playlist__add_songs") {
  242. activity.payload.message = `Added ${howManySongs} songs to playlist <playlistId>${payload.playlist.displayName}</playlistId>`;
  243. activity.type = "playlist__add_songs";
  244. }
  245. ActivitiesModule.runJob("ADD_ACTIVITY", activity, this)
  246. .then(() => next())
  247. .catch(next);
  248. }
  249. ],
  250. async err => {
  251. if (err) {
  252. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  253. return reject(new Error(err));
  254. }
  255. return resolve();
  256. }
  257. );
  258. });
  259. }
  260. /**
  261. * Hides any activities of the same type within a 15-minute period to prevent spam
  262. *
  263. * @param {object} payload - object that contains the payload
  264. * @param {string} payload.userId - the id of the user to check for duplicates
  265. * @param {string} payload.type - the type of activity to check for duplicates
  266. * @returns {Promise} - returns promise (reject, resolve)
  267. */
  268. async CHECK_FOR_ACTIVITY_SPAM_TO_HIDE(payload) {
  269. const activityModel = await DBModule.runJob("GET_MODEL", { modelName: "activity" }, this);
  270. return new Promise((resolve, reject) => {
  271. async.waterfall(
  272. [
  273. // find all activities of this type from the last 15 minutes
  274. next => {
  275. activityModel
  276. .find(
  277. {
  278. userId: payload.userId,
  279. type: payload.type,
  280. hidden: false,
  281. createdAt: {
  282. $gte: new Date(new Date() - 15 * 60 * 1000)
  283. }
  284. },
  285. "_id"
  286. )
  287. .sort({ createdAt: -1 })
  288. .skip(1)
  289. .exec(next);
  290. },
  291. // hide these activities and emit to socket listeners
  292. (activities, next) => {
  293. activities.forEach(activity => {
  294. activityModel.updateOne({ _id: activity._id }, { $set: { hidden: true } }).catch(next);
  295. WSModule.runJob("SOCKETS_FROM_USER", { userId: payload.userId }, this)
  296. .then(sockets =>
  297. sockets.forEach(socket => socket.dispatch("event:activity.hide", activity._id))
  298. )
  299. .catch(next);
  300. WSModule.runJob("EMIT_TO_ROOM", {
  301. room: `profile-${payload.userId}-activities`,
  302. args: ["event:activity.hide", activity._id]
  303. });
  304. });
  305. return next();
  306. }
  307. ],
  308. async err => {
  309. if (err) {
  310. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  311. return reject(new Error(err));
  312. }
  313. return resolve();
  314. }
  315. );
  316. });
  317. }
  318. }
  319. export default new _ActivitiesModule();