useYoutubeDirect.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. res => {
  63. if (res.status !== "success")
  64. new Toast(`Error: ${res.message}`);
  65. else {
  66. new Toast(res.message);
  67. youtubeDirect.value = "";
  68. }
  69. }
  70. );
  71. }
  72. };
  73. return {
  74. youtubeDirect,
  75. addToPlaylist,
  76. addToQueue,
  77. getYoutubeVideoId
  78. };
  79. };