Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions apps/client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import CollaborativeArtists from "./scenes/Collaborative/Affinity/Artists";
import "./App.css";
import RegistrationsDisabled from "./scenes/Error/RegistrationsDisabled";
import Affinity from "./scenes/Collaborative/Affinity";
import LikedSongs from "./scenes/Collaborative/LikedSongs";
import { useTheme } from "./services/theme";
import { selectDarkMode } from "./services/redux/modules/user/selector";
import PlaylistDialog from "./components/PlaylistDialog";
Expand Down Expand Up @@ -119,6 +120,14 @@ function App() {
</PrivateRoute>
}
/>
<Route
path="/collaborative/liked-songs"
element={
<PrivateRoute>
<LikedSongs />
</PrivateRoute>
}
/>
<Route
path="/collaborative/top/songs/:mode"
element={
Expand Down
11 changes: 10 additions & 1 deletion apps/client/src/components/Layout/Sider/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import {
ShareOutlined,
Speed,
SpeedOutlined,
OfflineShare,
OfflineShareOutlined,
} from "@mui/icons-material";

export interface SiderLink {
Expand Down Expand Up @@ -80,7 +82,7 @@ export const links: SiderCategory[] = [
],
},
{
label: "With people",
label: "Social",
items: [
{
label: "Affinity",
Expand All @@ -89,6 +91,13 @@ export const links: SiderCategory[] = [
iconOn: <MusicNote />,
restrict: "guest",
},
{
label: "Share liked songs",
link: "/collaborative/liked-songs",
icon: <OfflineShareOutlined />,
iconOn: <OfflineShare />,
restrict: "guest",
},
],
},
{
Expand Down
158 changes: 158 additions & 0 deletions apps/client/src/scenes/Collaborative/LikedSongs/LikedSongs.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import { useState, useEffect, useRef } from "react";
import Header from "../../../components/Header";
import Text from "../../../components/Text";
import s from "./index.module.css";
import { Button } from "@mui/material";
import { useAppDispatch } from "../../../services/redux/tools";
import { syncLikedSongsStatus, setSyncLikedSongs } from "../../../services/redux/modules/user/thunk";
import { alertMessage } from "../../../services/redux/modules/message/reducer";
import { selectUser } from "../../../services/redux/modules/user/selector";
import { useSelector } from "react-redux";
import { SyncLikedSongsStatusResponse, SyncLikedSongsResponse } from "../../../services/redux/modules/user/types";

export default function LikedSongs() {
const user = useSelector(selectUser);
const [likedSongsPlaylistId, setLikedSongsPlaylistId] = useState<string>("");
const [syncEnabled, setSyncEnabled] = useState<boolean>(false);
const [likedSongsLoading, setLoadingLikedSongs] = useState<boolean>(true);
const [showPlaylistEmbed, setShowPlaylistEmbed] = useState<boolean>(false);
const [timeoutId, setTimeoutId] = useState<NodeJS.Timeout | null>(null);
const dispatch = useAppDispatch();
const iframeRef = useRef<HTMLIFrameElement>(null);

if (!user) {
return null;
}

useEffect(() => {
const fetchInitialState = async () => {
try {
let enabled = user.syncLikedSongsStatus == "active" || user.syncLikedSongsStatus == "loading";
setSyncEnabled(enabled);
setShowPlaylistEmbed(enabled);
if (user.syncLikedSongsPlaylistId) {
setLikedSongsPlaylistId(user.syncLikedSongsPlaylistId);
}
} catch (error) {
console.error("Failed to fetch initial state:", error);
showRequestError();
} finally {
setLoadingLikedSongs(false);
}
};

fetchInitialState();
}, [user]);

const startRecursiveCheck = async (playlistId: string, count = 0) => {
if (count < 20) {
let result = (await dispatch(syncLikedSongsStatus())).payload as SyncLikedSongsStatusResponse;
if (result.success && result.status == "active") {
dispatch(alertMessage({
level: "success",
message: "Sync complete",
}));
return;
} else if (result.status == "failed") {
dispatch(alertMessage({
level: "error",
message: "Sync failed. Please try again later",
}));
return;
}

if (iframeRef.current) {
iframeRef.current.src = `https://open.spotify.com/embed/playlist/${playlistId}?cache=${new Date().getTime()}`;
const id = setTimeout(() => startRecursiveCheck(playlistId, count + 1), 3000);
setTimeoutId(id);
}
} else {
setTimeoutId(null);
}
};

const stopRecursiveCheck = () => {
if (timeoutId) {
clearTimeout(timeoutId);
setTimeoutId(null);
}
};

const toggleSync = async () => {
if (likedSongsLoading) return;

setLoadingLikedSongs(true);
const newSyncEnabled = !syncEnabled;

try {
let result = (await dispatch(setSyncLikedSongs(newSyncEnabled))).payload as SyncLikedSongsResponse;
if (result.success) {
setSyncEnabled(newSyncEnabled);
setShowPlaylistEmbed(newSyncEnabled);

if (newSyncEnabled) {
setTimeout(()=> {
setLikedSongsPlaylistId(result.playlistId);
startRecursiveCheck(result.playlistId);
}, 1000);
} else {
setLikedSongsPlaylistId("");
stopRecursiveCheck();
}
}
else {
showRequestError("Failed to update sync status");
}
} catch (error) {
console.error("Failed to update syncLikedSongs state:", error);
showRequestError();
} finally {
setLoadingLikedSongs(false);
}
};

const showRequestError = (msg: string = "The web application could not communicate with the server") => {
dispatch(alertMessage({
level: "error",
message: msg,
}));
}

return (
<div className={s.root}>
<Header
hideInterval
title={<div className={s.title}>Share liked songs</div>}
subtitle="Automatically syncs your liked songs into a shareable playlist every night"
/>
<div className={s.content}>
<div className={s.buttonContainer}>
<Text>Sync your liked songs:</Text>
<Button
className={s.syncButton}
variant="contained"
onClick={toggleSync}
disabled={likedSongsLoading} // Disable button while setLikedSongsLoading
>
{syncEnabled ? "On" : "Off"}
</Button>
</div>
<br></br>
{showPlaylistEmbed && (
<div className={s.embedContainer}>
<Text>Preview (press to open)</Text>
<iframe
ref={iframeRef}
className={s.embedPlaylist}
src={`https://open.spotify.com/embed/playlist/${likedSongsPlaylistId}?cache=${new Date().getTime()}`}
frameBorder="0"
allowFullScreen
allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
loading="lazy"
/>
</div>
)}
</div>
</div>
);
}
61 changes: 61 additions & 0 deletions apps/client/src/scenes/Collaborative/LikedSongs/index.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
.root {
margin: auto;
height: 100vh;
display: flex;
flex-direction: column;
}

.title {
display: flex;
flex-direction: row;
align-items: center;
}

.content {
margin-top: 15px;
}

.syncButton {
width: fit-content;
margin-left: 20px !important;
}

.buttonContainer {
margin: 15px auto 0px auto;
width: fit-content;
}

.embedContainer {
text-align: center;
}

.embedContainer iframe {
margin-top: 8px;
display: block;
}

.embedPlaylist {
border-radius: 12px;
width: 88vw;
margin: 0px auto;
}

@media (min-width: 885px) {
.content {
margin: 15px;
}
.buttonContainer {
width: initial;
}
.embedContainer {
text-align: left;
}
.embedContainer span {
display: none;
}
.embedPlaylist {
width: 700px;
height: 60vh;
margin: 0px;
}
}
1 change: 1 addition & 0 deletions apps/client/src/scenes/Collaborative/LikedSongs/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "./LikedSongs";
7 changes: 6 additions & 1 deletion apps/client/src/services/apis/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Axios from "axios";
import { AdminAccount } from "../redux/modules/admin/reducer";
import { ImporterState } from "../redux/modules/import/types";
import { Playlist, PlaylistContext } from "../redux/modules/playlist/types";
import { User } from "../redux/modules/user/types";
import { SyncLikedSongsResponse, SyncLikedSongsStatusResponse, User } from "../redux/modules/user/types";
import {
Album,
Artist,
Expand Down Expand Up @@ -549,6 +549,11 @@ export const api = {
};
}[]
>("/spotify/top/sessions", { start, end }),
setSyncLikedSongs: (status: boolean) =>
post<SyncLikedSongsResponse>("/spotify/sync-liked-songs", {
status,
}),
syncLikedSongsStatus: () => get<SyncLikedSongsStatusResponse>("/spotify/sync-liked-songs-status"),
};

export const DEFAULT_ITEMS_TO_LOAD = 20;
Expand Down
9 changes: 8 additions & 1 deletion apps/client/src/services/redux/modules/playlist/types.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { CollaborativeMode, SpotifyImage } from "../../../types";
import { CollaborativeMode, SpotifyImage, Track } from "../../../types";

export interface Playlist {
id: string;
name: string;
owner: {
id: string;
};
images: SpotifyImage[];
tracks: {
total: number;
items: Track[];
};
}

export interface PlaylistTopSongsContext {
Expand Down
42 changes: 41 additions & 1 deletion apps/client/src/services/redux/modules/user/thunk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { DateFormatter } from "../../../date";
import { myAsyncThunk } from "../../tools";
import { alertMessage } from "../message/reducer";
import { selectIsPublic } from "./selector";
import { DarkModeType, User } from "./types";
import { DarkModeType, SyncLikedSongsResponse, SyncLikedSongsStatusResponse, User } from "./types";

export const checkLogged = myAsyncThunk<User | null, void>(
"@user/checklogged",
Expand Down Expand Up @@ -181,3 +181,43 @@ export const unblacklistArtist = myAsyncThunk<void, string>(
}
},
);

export const setSyncLikedSongs = myAsyncThunk<SyncLikedSongsResponse, boolean>(
"@user/set-sync-liked-songs",
async (status, tapi) => {
try {
const resp: SyncLikedSongsResponse = (await api.setSyncLikedSongs(status)).data;
await tapi.dispatch(checkLogged());
return resp;
} catch (e) {
console.error(e);
tapi.dispatch(
alertMessage({
level: "error",
message: `Could not update sync liked songs to ${status}`,
}),
);
return { success: false, playlistId: "" } as SyncLikedSongsResponse;
}
},
);

export const syncLikedSongsStatus = myAsyncThunk<SyncLikedSongsStatusResponse, void>(
"@user/sync-liked-songs-status",
async (_, tapi) => {
try {
const resp: SyncLikedSongsStatusResponse = (await api.syncLikedSongsStatus()).data;
await tapi.dispatch(checkLogged());
return resp;
} catch (e) {
console.error(e);
tapi.dispatch(
alertMessage({
level: "error",
message: "Could not get loading state of sync",
}),
);
return { success: false, status: "failed", error: e } as SyncLikedSongsStatusResponse;
}
},
);
13 changes: 13 additions & 0 deletions apps/client/src/services/redux/modules/user/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,19 @@ export interface User {
publicToken: string | null;
firstListenedAt: string;
isGuest: boolean;
syncLikedSongsPlaylistId: string | null;
syncLikedSongsStatus: "inactive" | "active" | "loading" | "failed";
}

export interface SyncLikedSongsResponse {
success: boolean;
playlistId: string;
}

export interface SyncLikedSongsStatusResponse {
success: boolean;
status: "inactive" | "active" | "loading" | "failed";
error?: string;
}

export interface ReduxPresetIntervalDetail {
Expand Down
Loading