Browse Source

refactor(Stations): cleaned up favoriting/unfavoriting code

Signed-off-by: Jonathan <theflametrooper@gmail.com>
Jonathan 4 years ago
parent
commit
6b99371741

+ 44 - 7
backend/logic/actions/stations.js

@@ -355,6 +355,22 @@ export default {
 						(station, next) => {
 							async.waterfall(
 								[
+									next => {
+										StationsModule.runJob(
+											"HAS_USER_FAVORITED_STATION",
+											{
+												userId: session.userId,
+												stationId: station._id
+											},
+											this
+										)
+											.then(isStationFavorited => {
+												station.isFavorited = isStationFavorited;
+												return next();
+											})
+											.catch(err => next(err));
+									},
+
 									next => {
 										StationsModule.runJob(
 											"CAN_USER_VIEW_STATION",
@@ -365,15 +381,15 @@ export default {
 											},
 											this
 										)
-											.then(exists => {
-												next(null, exists);
-											})
+											.then(exists => next(null, exists))
 											.catch(next);
 									}
 								],
 								(err, exists) => {
 									if (err) this.log(err);
+
 									station.userCount = StationsModule.usersPerStationCount[station._id] || 0;
+
 									if (exists) filteredStations.push(station);
 									next();
 								}
@@ -614,6 +630,7 @@ export default {
 						socketId: session.socketId,
 						room: `station.${station._id}`
 					});
+
 					const data = {
 						_id: station._id,
 						type: station.type,
@@ -632,20 +649,27 @@ export default {
 						genres: station.genres,
 						blacklistedGenres: station.blacklistedGenres
 					};
+
 					StationsModule.userList[session.socketId] = station._id;
+
 					next(null, data);
 				},
 
 				(data, next) => {
 					data = JSON.parse(JSON.stringify(data));
+
 					data.userCount = StationsModule.usersPerStationCount[data._id] || 0;
 					data.users = StationsModule.usersPerStation[data._id] || [];
+
 					if (!data.currentSong || !data.currentSong.title) return next(null, data);
+
 					IOModule.runJob("SOCKET_JOIN_SONG_ROOM", {
 						socketId: session.socketId,
 						room: `song.${data.currentSong.songId}`
 					});
+
 					data.currentSong.skipVotes = data.currentSong.skipVotes.length;
+
 					return SongsModule.runJob(
 						"GET_SONG_FROM_ID",
 						{
@@ -667,10 +691,23 @@ export default {
 							data.currentSong.likes = -1;
 							data.currentSong.dislikes = -1;
 						})
-						.finally(() => {
-							next(null, data);
-						});
-				}
+						.finally(() => next(null, data));
+				},
+
+				(data, next) =>
+					StationsModule.runJob(
+						"HAS_USER_FAVORITED_STATION",
+						{
+							userId: session.userId,
+							stationId: data._id
+						},
+						this
+					)
+						.then(isStationFavorited => {
+							data.isFavorited = isStationFavorited;
+							return next(null, data);
+						})
+						.catch(err => next(err))
 			],
 			async (err, data) => {
 				if (err) {

+ 0 - 33
backend/logic/actions/users.js

@@ -1932,38 +1932,5 @@ export default {
 				}
 			}
 		);
-	}),
-
-	getFavoriteStations: isLoginRequired(async function getFavoriteStations(session, cb) {
-		const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
-		async.waterfall(
-			[
-				next => {
-					userModel.findOne({ _id: session.userId }, next);
-				},
-
-				(user, next) => {
-					if (!user) return next("User not found.");
-					return next(null, user);
-				}
-			],
-			async (err, user) => {
-				if (err && err !== true) {
-					err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
-					this.log(
-						"ERROR",
-						"GET_FAVORITE_STATIONS",
-						`User ${session.userId} failed to get favorite stations. '${err}'`
-					);
-					cb({ status: "failure", message: err });
-				} else {
-					this.log("SUCCESS", "GET_FAVORITE_STATIONS", `User ${session.userId} got favorite stations.`);
-					cb({
-						status: "success",
-						favoriteStations: user.favoriteStations
-					});
-				}
-			}
-		);
 	})
 };

+ 42 - 0
backend/logic/stations.js

@@ -1086,6 +1086,48 @@ class _StationsModule extends CoreClass {
 		});
 	}
 
+	/**
+	 * Checks if a user has favorited a station or not
+	 *
+	 * @param {object} payload - object that contains the payload
+	 * @param {object} payload.stationId - the id of the station in question
+	 * @param {string} payload.userId - the id of the user in question
+	 * @returns {Promise} - returns a promise (resolve, reject)
+	 */
+	HAS_USER_FAVORITED_STATION(payload) {
+		return new Promise((resolve, reject) => {
+			async.waterfall(
+				[
+					next => {
+						DBModule.runJob(
+							"GET_MODEL",
+							{
+								modelName: "user"
+							},
+							this
+						).then(userModel => {
+							userModel.findOne({ _id: payload.userId }, next);
+						});
+					},
+
+					(user, next) => {
+						if (!user) return next("User not found.");
+						if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
+						return next(null, false);
+					}
+				],
+				async (err, isStationFavorited) => {
+					if (err && err !== true) {
+						err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
+						return reject(new Error(err));
+					}
+
+					return resolve(isStationFavorited);
+				}
+			);
+		});
+	}
+
 	/**
 	 * Returns a list of sockets in a room that can and can't know about a station
 	 *

+ 22 - 21
frontend/src/pages/Home/index.vue

@@ -63,16 +63,14 @@
 						<div class="media">
 							<div class="media-left displayName">
 								<i
-									v-if="loggedIn && !isFavorite(station)"
-									@click.prevent="addFavoriteStation(station)"
+									v-if="loggedIn && !station.isFavorited"
+									@click.prevent="favoriteStation(station)"
 									class="favorite material-icons"
 									>star_border</i
 								>
 								<i
-									v-if="loggedIn && isFavorite(station)"
-									@click.prevent="
-										removeFavoriteStation(station)
-									"
+									v-if="loggedIn && station.isFavorited"
+									@click.prevent="unfavoriteStation(station)"
 									class="favorite material-icons"
 									>star</i
 								>
@@ -187,7 +185,6 @@ export default {
 				key: ""
 			},
 			stations: [],
-			favoriteStations: [],
 			searchQuery: ""
 		};
 	},
@@ -208,7 +205,7 @@ export default {
 				)
 				.sort(
 					(a, b) =>
-						this.isFavorite(b) - this.isFavorite(a) ||
+						b.isFavorited - a.isFavorited ||
 						this.isOwner(b) - this.isOwner(a) ||
 						this.isPlaying(b) - this.isPlaying(a) ||
 						a.paused - b.paused ||
@@ -347,12 +344,21 @@ export default {
 			});
 
 			this.socket.on("event:user.favoritedStation", stationId => {
-				this.favoriteStations.push(stationId);
+				this.stations.forEach(s => {
+					const station = s;
+					if (station._id === stationId) {
+						station.isFavorited = true;
+					}
+				});
 			});
 
 			this.socket.on("event:user.unfavoritedStation", stationId => {
-				const index = this.favoriteStations.indexOf(stationId);
-				this.favoriteStations.splice(index, 1);
+				this.stations.forEach(s => {
+					const station = s;
+					if (station._id === stationId) {
+						station.isFavorited = false;
+					}
+				});
 			});
 		});
 	},
@@ -375,22 +381,16 @@ export default {
 						this.stations.push(station);
 					});
 			});
-			this.socket.emit("users.getFavoriteStations", data => {
-				if (data.status === "success")
-					this.favoriteStations = data.favoriteStations;
-			});
+
 			this.socket.emit("apis.joinRoom", "home", () => {});
 		},
 		isOwner(station) {
 			return station.owner === this.userId;
 		},
-		isFavorite(station) {
-			return this.favoriteStations.indexOf(station._id) !== -1;
-		},
 		isPlaying(station) {
 			return typeof station.currentSong.title !== "undefined";
 		},
-		addFavoriteStation(station) {
+		favoriteStation(station) {
 			this.socket.emit("stations.favoriteStation", station._id, res => {
 				if (res.status === "success") {
 					new Toast({
@@ -400,7 +400,7 @@ export default {
 				} else new Toast({ content: res.message, timeout: 8000 });
 			});
 		},
-		removeFavoriteStation(station) {
+		unfavoriteStation(station) {
 			this.socket.emit("stations.unfavoriteStation", station._id, res => {
 				if (res.status === "success") {
 					new Toast({
@@ -410,7 +410,8 @@ export default {
 				} else new Toast({ content: res.message, timeout: 8000 });
 			});
 		},
-		...mapActions("modals", ["openModal"])
+		...mapActions("modals", ["openModal"]),
+		...mapActions("station", ["updateIfStationIsFavorited"])
 	}
 };
 </script>

+ 15 - 22
frontend/src/pages/Station/index.vue

@@ -22,14 +22,14 @@
 							<a href="#">
 								<!-- Favorite Station Button -->
 								<i
-									v-if="loggedIn && favoriteStation"
-									@click.prevent="removefavoriteStation()"
+									v-if="loggedIn && station.isFavorited"
+									@click.prevent="unfavoriteStation()"
 									class="material-icons"
 									>star</i
 								>
 								<i
-									v-if="loggedIn && !favoriteStation"
-									@click.prevent="addFavoriteStation()"
+									v-if="loggedIn && !station.isFavorited"
+									@click.prevent="favoriteStation()"
 									class="material-icons"
 									>star_border</i
 								>
@@ -406,7 +406,6 @@ export default {
 			seeking: false,
 			playbackRate: 1,
 			volumeSliderValue: 0,
-			favoriteStation: false,
 			showPlaylistDropdown: false
 		};
 	},
@@ -613,12 +612,13 @@ export default {
 			});
 
 			this.socket.on("event:user.favoritedStation", stationId => {
-				if (stationId === this.station._id) this.favoriteStation = true;
+				if (stationId === this.station._id)
+					this.updateIfStationIsFavorited({ isFavorited: true });
 			});
 
 			this.socket.on("event:user.unfavoritedStation", stationId => {
 				if (stationId === this.station._id)
-					this.favoriteStation = false;
+					this.updateIfStationIsFavorited({ isFavorited: false });
 			});
 		});
 
@@ -1207,7 +1207,8 @@ export default {
 						privatePlaylist,
 						type,
 						genres,
-						blacklistedGenres
+						blacklistedGenres,
+						isFavorited
 					} = res.data;
 
 					this.joinStation({
@@ -1222,7 +1223,8 @@ export default {
 						privatePlaylist,
 						type,
 						genres,
-						blacklistedGenres
+						blacklistedGenres,
+						isFavorited
 					});
 
 					const currentSong = res.data.currentSong
@@ -1271,16 +1273,6 @@ export default {
 						});
 					}
 
-					/** Check if station is favorited */
-					this.socket.emit("users.getFavoriteStations", data => {
-						if (
-							data.status === "success" &&
-							data.favoriteStations.indexOf(this.station._id) !==
-								-1
-						)
-							this.favoriteStation = true;
-					});
-
 					if (this.isOwnerOrAdmin()) {
 						keyboardShortcuts.registerShortcut(
 							"station.pauseResume",
@@ -1404,7 +1396,7 @@ export default {
 				}
 			});
 		},
-		addFavoriteStation() {
+		favoriteStation() {
 			this.socket.emit(
 				"stations.favoriteStation",
 				this.station._id,
@@ -1418,7 +1410,7 @@ export default {
 				}
 			);
 		},
-		removeFavoriteStation() {
+		unfavoriteStation() {
 			this.socket.emit(
 				"stations.unfavoriteStation",
 				this.station._id,
@@ -1443,7 +1435,8 @@ export default {
 			"updateStationPaused",
 			"updateLocalPaused",
 			"updateNoSong",
-			"editStation"
+			"editStation",
+			"updateIfStationIsFavorited"
 		])
 	}
 };

+ 6 - 0
frontend/src/store/modules/station.js

@@ -49,6 +49,9 @@ const actions = {
 	},
 	updatePrivatePlaylistQueueSelected: ({ commit }, status) => {
 		commit("updatePrivatePlaylistQueueSelected", status);
+	},
+	updateIfStationIsFavorited: ({ commit }, { isFavorited }) => {
+		commit("updateIfStationIsFavorited", isFavorited);
 	}
 };
 
@@ -92,6 +95,9 @@ const mutations = {
 	},
 	updatePrivatePlaylistQueueSelected(state, status) {
 		state.privatePlaylistQueueSelected = status;
+	},
+	updateIfStationIsFavorited(state, isFavorited) {
+		state.station.isFavorited = isFavorited;
 	}
 };