activities.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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.youtubeId - (optional) if relevant, the youtube 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 =>
  67. socket.dispatch("event:activity.create", { data: { activity } })
  68. );
  69. next(null, activity);
  70. })
  71. .catch(next);
  72. },
  73. (activity, next) => {
  74. WSModule.runJob("EMIT_TO_ROOM", {
  75. room: `profile-${activity.userId}-activities`,
  76. args: ["event:activity.create", { data: { activity } }]
  77. });
  78. return next(null, activity);
  79. },
  80. (activity, next) => {
  81. const mergeableActivities = ["playlist__remove_song", "playlist__add_song"];
  82. const spammableActivities = [
  83. "user__toggle_nightmode",
  84. "user__toggle_autoskip_disliked_songs",
  85. "user__toggle_activity_watch",
  86. "song__like",
  87. "song__unlike",
  88. "song__dislike",
  89. "song__undislike"
  90. ];
  91. CacheModule.runJob("HGET", { table: "recentActivities", key: activity.userId })
  92. .then(recentActivity => {
  93. if (recentActivity) {
  94. const timeDifference = mins =>
  95. new Date() - new Date(recentActivity.createdAt) < mins * 60 * 1000;
  96. // if both activities have the same type, if within last 15 mins and if activity is within the spammableActivities array
  97. if (
  98. recentActivity.type === activity.type &&
  99. !!timeDifference(15) &&
  100. spammableActivities.includes(activity.type)
  101. )
  102. return ActivitiesModule.runJob(
  103. "CHECK_FOR_ACTIVITY_SPAM_TO_HIDE",
  104. { userId: activity.userId, type: activity.type },
  105. this
  106. )
  107. .then(() => next(null, activity))
  108. .catch(next);
  109. // if activity is within the mergeableActivities array, if both activities are about removing/adding and if within last 5 mins
  110. if (
  111. mergeableActivities.includes(activity.type) &&
  112. recentActivity.type === activity.type &&
  113. !!timeDifference(5)
  114. ) {
  115. return PlaylistsModule.runJob("GET_PLAYLIST", {
  116. playlistId: activity.payload.playlistId
  117. })
  118. .then(playlist =>
  119. ActivitiesModule.runJob(
  120. "CHECK_FOR_ACTIVITY_SPAM_TO_MERGE",
  121. {
  122. userId: activity.userId,
  123. type: activity.type,
  124. playlist: {
  125. playlistId: playlist._id,
  126. displayName: playlist.displayName
  127. }
  128. },
  129. this
  130. )
  131. .then(() => next(null, activity))
  132. .catch(next)
  133. )
  134. .catch(next);
  135. }
  136. return next(null, activity);
  137. }
  138. return next(null, activity);
  139. })
  140. .catch(next);
  141. },
  142. // store most recent activity in cache to be quickly accessible
  143. (activity, next) =>
  144. CacheModule.runJob(
  145. "HSET",
  146. {
  147. table: "recentActivities",
  148. key: activity.userId,
  149. value: { createdAt: activity.createdAt, type: activity.type }
  150. },
  151. this
  152. )
  153. .then(() => next(null))
  154. .catch(next)
  155. ],
  156. async (err, activity) => {
  157. if (err) {
  158. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  159. return reject(new Error(err));
  160. }
  161. return resolve(activity);
  162. }
  163. );
  164. });
  165. }
  166. /**
  167. * Merges activities about adding/removing songs from a playlist within a 5-minute period to prevent spam
  168. *
  169. * @param {object} payload - object that contains the payload
  170. * @param {string} payload.userId - the id of the user to check for duplicates
  171. * @param {object} payload.playlist - object that contains info about the relevant playlist
  172. * @param {string} payload.playlist.playlistId - the id of the playlist
  173. * @param {string} payload.playlist.displayName - the display name of the playlist
  174. * @param {string} payload.type - the type of activity to check for duplicates
  175. * @returns {Promise} - returns promise (reject, resolve)
  176. */
  177. async CHECK_FOR_ACTIVITY_SPAM_TO_MERGE(payload) {
  178. const activityModel = await DBModule.runJob("GET_MODEL", { modelName: "activity" }, this);
  179. return new Promise((resolve, reject) => {
  180. async.waterfall(
  181. [
  182. // find all activities of this type from the last 5 minutes
  183. next => {
  184. activityModel
  185. .find(
  186. {
  187. userId: payload.userId,
  188. type: { $in: [payload.type, `${payload.type}s`] },
  189. hidden: false,
  190. createdAt: {
  191. $gte: new Date(new Date() - 5 * 60 * 1000)
  192. },
  193. "payload.playlistId": payload.playlist.playlistId
  194. },
  195. ["_id", "type", "payload.message"]
  196. )
  197. .sort({ createdAt: -1 })
  198. .exec(next);
  199. },
  200. // hide these activities, emit to socket listeners and count number of songs in each
  201. (activities, next) => {
  202. let howManySongs = 0; // how many songs added/removed
  203. activities.forEach(activity => {
  204. activityModel.updateOne({ _id: activity._id }, { $set: { hidden: true } }).catch(next);
  205. WSModule.runJob("SOCKETS_FROM_USER", { userId: payload.userId }, this)
  206. .then(sockets =>
  207. sockets.forEach(socket =>
  208. socket.dispatch("event:activity.hide", { data: { activityId: activity._id } })
  209. )
  210. )
  211. .catch(next);
  212. WSModule.runJob("EMIT_TO_ROOM", {
  213. room: `profile-${payload.userId}-activities`,
  214. args: ["event:activity.hide", { data: { activityId: activity._id } }]
  215. });
  216. if (activity.type === payload.type) howManySongs += 1;
  217. else if (activity.type === `${payload.type}s`)
  218. howManySongs += parseInt(
  219. activity.payload.message.replace(
  220. /(?:Removed|Added)\s(?<songs>\d+)\ssongs.+/g,
  221. "$<songs>"
  222. )
  223. );
  224. });
  225. return next(null, howManySongs);
  226. },
  227. // // delete in cache the most recent activity to avoid issues when adding a new activity
  228. (howManySongs, next) => {
  229. CacheModule.runJob("HDEL", { table: "recentActivities", key: payload.userId }, this)
  230. .then(() => next(null, howManySongs))
  231. .catch(next);
  232. },
  233. // add a new activity that merges the activities together
  234. (howManySongs, next) => {
  235. const activity = {
  236. userId: payload.userId,
  237. type: "",
  238. payload: {
  239. message: "",
  240. playlistId: payload.playlist.playlistId
  241. }
  242. };
  243. if (payload.type === "playlist__remove_song" || payload.type === "playlist__remove_songs") {
  244. activity.payload.message = `Removed ${howManySongs} songs from playlist <playlistId>${payload.playlist.displayName}</playlistId>`;
  245. activity.type = "playlist__remove_songs";
  246. } else if (payload.type === "playlist__add_song" || payload.type === "playlist__add_songs") {
  247. activity.payload.message = `Added ${howManySongs} songs to playlist <playlistId>${payload.playlist.displayName}</playlistId>`;
  248. activity.type = "playlist__add_songs";
  249. }
  250. ActivitiesModule.runJob("ADD_ACTIVITY", activity, this)
  251. .then(() => next())
  252. .catch(next);
  253. }
  254. ],
  255. async err => {
  256. if (err) {
  257. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  258. return reject(new Error(err));
  259. }
  260. return resolve();
  261. }
  262. );
  263. });
  264. }
  265. /**
  266. * Hides any activities of the same type within a 15-minute period to prevent spam
  267. *
  268. * @param {object} payload - object that contains the payload
  269. * @param {string} payload.userId - the id of the user to check for duplicates
  270. * @param {string} payload.type - the type of activity to check for duplicates
  271. * @returns {Promise} - returns promise (reject, resolve)
  272. */
  273. async CHECK_FOR_ACTIVITY_SPAM_TO_HIDE(payload) {
  274. const activityModel = await DBModule.runJob("GET_MODEL", { modelName: "activity" }, this);
  275. return new Promise((resolve, reject) => {
  276. async.waterfall(
  277. [
  278. // find all activities of this type from the last 15 minutes
  279. next => {
  280. activityModel
  281. .find(
  282. {
  283. userId: payload.userId,
  284. type: payload.type,
  285. hidden: false,
  286. createdAt: {
  287. $gte: new Date(new Date() - 15 * 60 * 1000)
  288. }
  289. },
  290. "_id"
  291. )
  292. .sort({ createdAt: -1 })
  293. .skip(1)
  294. .exec(next);
  295. },
  296. // hide these activities and emit to socket listeners
  297. (activities, next) => {
  298. activities.forEach(activity => {
  299. activityModel.updateOne({ _id: activity._id }, { $set: { hidden: true } }).catch(next);
  300. WSModule.runJob("SOCKETS_FROM_USER", { userId: payload.userId }, this)
  301. .then(sockets =>
  302. sockets.forEach(socket =>
  303. socket.dispatch("event:activity.hide", { data: { activityId: activity._id } })
  304. )
  305. )
  306. .catch(next);
  307. WSModule.runJob("EMIT_TO_ROOM", {
  308. room: `profile-${payload.userId}-activities`,
  309. args: ["event:activity.hide", { data: { activityId: activity._id } }]
  310. });
  311. });
  312. return next();
  313. }
  314. ],
  315. async err => {
  316. if (err) {
  317. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  318. return reject(new Error(err));
  319. }
  320. return resolve();
  321. }
  322. );
  323. });
  324. }
  325. }
  326. export default new _ActivitiesModule();