Guest User

Untitled

a guest
Oct 21st, 2024
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const listensContainer = document.getElementById('listens-container');
  2. const addButton = document.getElementById('add-button');
  3.  
  4. // Your ListenBrainz token and username
  5. const listenBrainzToken = '6666';
  6. let username = '';
  7.  
  8. // Function to fetch listens from ListenBrainz
  9. async function fetchListens() {
  10.   // Get username from input field
  11.   username = document.getElementById('username').value;
  12.   const debugContainer = document.createElement('div');  // For displaying debug info
  13.   listensContainer.appendChild(debugContainer);          // Append debug container to listens container
  14.  
  15.   if (!username) {
  16.     alert('Please enter a username.');
  17.     return;
  18.   }
  19.  
  20.   // Clear any previous debug info
  21.   debugContainer.innerHTML = '';
  22.  
  23.  
  24.   try {
  25.     const response = await fetch(`https://api.listenbrainz.org/1/user/${username}/listens?count=10`, {
  26.       headers: {
  27.         'Authorization': `Token ${listenBrainzToken}`
  28.       }
  29.     });
  30.  
  31.     // Log response status and headers for further debugging
  32.     console.log('Status Code:', response.status);
  33.     console.log('Headers:', response.headers);
  34.  
  35.     // Display response status on the page
  36.     debugContainer.innerHTML = `<p>Status Code: ${response.status}</p>`;
  37.  
  38.     // Check if response status is not OK (200)
  39.     if (!response.ok) {
  40.       throw new Error(`API request failed with status code: ${response.status}`);
  41.     }
  42.  
  43.     // Parse the response as JSON
  44.     const data = await response.json();
  45.  
  46.     // Display the full API response on the page for debugging
  47.     debugContainer.innerHTML += `<pre>Full API Response: ${JSON.stringify(data, null, 2)}</pre>`;
  48.  
  49.     // Log the full API response to console for debugging
  50.     console.log('Full API Response:', data);
  51.  
  52.     // Now fetch the listens from the correct payload field
  53.     if (data && data.payload && data.payload.listens) {
  54.       displayListens(data.payload.listens);
  55.       addButton.style.display = 'block';  // Show 'Add to Playlist' button once listens are displayed
  56.     } else {
  57.       throw new Error('No listens found or incorrect response structure.');
  58.     }
  59.  
  60.   } catch (error) {
  61.     // Display the error message on the page
  62.     debugContainer.innerHTML += `<p>Error: ${error.message}</p>`;
  63.     console.error('Error:', error);
  64.   }
  65. }
  66.  
  67. // Function to display listens in the UI
  68. function displayListens(listens) {
  69.   listensContainer.innerHTML = '';  // Clear previous listens
  70.  
  71.   if (listens.length === 0) {
  72.     listensContainer.innerHTML = '<p>No listens found for this user.</p>';
  73.     return;
  74.   }
  75.  
  76.   listens.forEach((listen, index) => {
  77.     const trackMetadata = listen.track_metadata;
  78.     const recordingMbid = trackMetadata.mbid_mapping ? trackMetadata.mbid_mapping.recording_mbid : null;
  79.     const artistName = trackMetadata.artist_name;
  80.     const trackName = trackMetadata.track_name;
  81.  
  82.     const listenItem = document.createElement('div');
  83.     listenItem.classList.add('listen-item');
  84.     listenItem.innerHTML = `
  85.       <input type="checkbox" id="listen-${index}" value="${recordingMbid}">
  86.       <label for="listen-${index}">${trackName} by ${artistName}</label>
  87.     `;
  88.     listensContainer.appendChild(listenItem);
  89.   });
  90. }
  91.  
  92. // Function to add selected listens to playlist
  93. async function addToPlaylist() {
  94.   const selectedListens = [];
  95.   const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
  96.  
  97.   checkboxes.forEach((checkbox) => {
  98.     selectedListens.push(checkbox.value);  // Grab the recording MBID
  99.   });
  100.  
  101.   if (selectedListens.length > 0) {
  102.     console.log("Selected listens:", selectedListens);  // Log the selected listens for debugging
  103.     await sendToPlaylist(selectedListens);
  104.   } else {
  105.     alert('No listens selected!');
  106.   }
  107. }
  108.  
  109. // Function to send selected listens to the playlist
  110. async function sendToPlaylist(selectedListens) {
  111.   const playlistMbid = '191af5d4-4d57-4ed1-ac03-e31badff7cd2';  // Your provided playlist MBID
  112.  
  113.   try {
  114.     const response = await fetch(`https://api.listenbrainz.org/1/playlist/${playlistMbid}/item-add`, {
  115.       method: 'POST',
  116.       headers: {
  117.         'Authorization': `Token ${listenBrainzToken}`,
  118.         'Content-Type': 'application/json'
  119.       },
  120.       body: JSON.stringify({
  121.         recording_mbid: selectedListens
  122.       })
  123.     });
  124.  
  125.     if (response.ok) {
  126.       alert('Successfully added to playlist!');
  127.     } else {
  128.       const responseText = await response.text(); // Get the error text if available
  129.       console.error("Response Error Text:", responseText);  // Log the error text
  130.       throw new Error(`Failed to add to playlist: ${response.status} - ${responseText}`);
  131.     }
  132.   } catch (error) {
  133.     alert(`Error: ${error.message}`);
  134.     console.error('Error:', error);
  135.   }
  136. }
Advertisement
Add Comment
Please, Sign In to add comment