useYoutubeDirect.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 youtubeVideoUrlRegex =
  6. /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/(watch\?v=)?([\w-]{11})$/;
  7. const youtubeVideoIdRegex = /^([\w-]{11})$/;
  8. export const useYoutubeDirect = () => {
  9. const youtubeDirect = ref("");
  10. const { socket } = useWebsocketsStore();
  11. const getYoutubeVideoId = () => {
  12. const youtubeVideoUrlParts = youtubeVideoUrlRegex.exec(
  13. youtubeDirect.value.trim()
  14. );
  15. if (youtubeVideoUrlParts) {
  16. // eslint-disable-next-line prefer-destructuring
  17. return youtubeVideoUrlParts[5];
  18. }
  19. const youtubeVideoIdParts = youtubeVideoIdRegex.exec(
  20. youtubeDirect.value.trim()
  21. );
  22. if (youtubeVideoIdParts) {
  23. // eslint-disable-next-line prefer-destructuring
  24. return youtubeVideoIdParts[1];
  25. }
  26. return null;
  27. };
  28. const addToPlaylist = (playlistId: string) => {
  29. const youtubeVideoId = getYoutubeVideoId();
  30. if (!youtubeVideoId)
  31. new Toast(
  32. `Could not determine the YouTube video id from the provided URL.`
  33. );
  34. else {
  35. socket.dispatch(
  36. "playlists.addSongToPlaylist",
  37. false,
  38. youtubeVideoId,
  39. playlistId,
  40. (res: AddSongToPlaylistResponse) => {
  41. if (res.status !== "success")
  42. new Toast(`Error: ${res.message}`);
  43. else {
  44. new Toast(res.message);
  45. youtubeDirect.value = "";
  46. }
  47. }
  48. );
  49. }
  50. };
  51. const addToQueue = (stationId: string) => {
  52. const youtubeVideoId = getYoutubeVideoId();
  53. if (!youtubeVideoId)
  54. new Toast(
  55. `Could not determine the YouTube video id from the provided URL.`
  56. );
  57. else {
  58. socket.dispatch(
  59. "stations.addToQueue",
  60. stationId,
  61. youtubeVideoId,
  62. "manual",
  63. res => {
  64. if (res.status !== "success")
  65. new Toast(`Error: ${res.message}`);
  66. else {
  67. new Toast(res.message);
  68. youtubeDirect.value = "";
  69. }
  70. }
  71. );
  72. }
  73. };
  74. return {
  75. youtubeDirect,
  76. addToPlaylist,
  77. addToQueue,
  78. getYoutubeVideoId
  79. };
  80. };