useSpotifyDirect.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { ref } from "vue";
  2. import Toast from "toasters";
  3. import { AddSongToPlaylistResponse } from "@musare_types/actions/PlaylistsActions";
  4. import { useWebsocketsStore } from "@/stores/websockets";
  5. const spotifyTrackUrlRegex =
  6. /.+open\.spotify\.com\/track\/(?<trackId>[A-Za-z0-9]+)/;
  7. export const useSpotifyDirect = () => {
  8. const spotifyDirect = ref("");
  9. const { socket } = useWebsocketsStore();
  10. const getSpotifyTrackId = () => {
  11. const match = spotifyTrackUrlRegex.exec(spotifyDirect.value.trim());
  12. if (!match || !match.groups) return null;
  13. const { trackId } = match.groups;
  14. return trackId;
  15. };
  16. const addToPlaylist = (playlistId: string) => {
  17. const spotifyTrackId = getSpotifyTrackId();
  18. if (!spotifyTrackId)
  19. new Toast(
  20. `Could not determine the Spotify track id from the provided URL.`
  21. );
  22. else {
  23. socket.dispatch(
  24. "playlists.addSongToPlaylist",
  25. false,
  26. `spotify:${spotifyTrackId}`,
  27. playlistId,
  28. (res: AddSongToPlaylistResponse) => {
  29. if (res.status !== "success")
  30. new Toast(`Error: ${res.message}`);
  31. else {
  32. new Toast(res.message);
  33. spotifyDirect.value = "";
  34. }
  35. }
  36. );
  37. }
  38. };
  39. return {
  40. spotifyDirect,
  41. addToPlaylist
  42. };
  43. };