Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const listensContainer = document.getElementById('listens-container');
- const addButton = document.getElementById('add-button');
- // Your ListenBrainz token and username
- const listenBrainzToken = '6666';
- let username = '';
- // Function to fetch listens from ListenBrainz
- async function fetchListens() {
- // Get username from input field
- username = document.getElementById('username').value;
- const debugContainer = document.createElement('div'); // For displaying debug info
- listensContainer.appendChild(debugContainer); // Append debug container to listens container
- if (!username) {
- alert('Please enter a username.');
- return;
- }
- // Clear any previous debug info
- debugContainer.innerHTML = '';
- try {
- const response = await fetch(`https://api.listenbrainz.org/1/user/${username}/listens?count=10`, {
- headers: {
- 'Authorization': `Token ${listenBrainzToken}`
- }
- });
- // Log response status and headers for further debugging
- console.log('Status Code:', response.status);
- console.log('Headers:', response.headers);
- // Display response status on the page
- debugContainer.innerHTML = `<p>Status Code: ${response.status}</p>`;
- // Check if response status is not OK (200)
- if (!response.ok) {
- throw new Error(`API request failed with status code: ${response.status}`);
- }
- // Parse the response as JSON
- const data = await response.json();
- // Display the full API response on the page for debugging
- debugContainer.innerHTML += `<pre>Full API Response: ${JSON.stringify(data, null, 2)}</pre>`;
- // Log the full API response to console for debugging
- console.log('Full API Response:', data);
- // Now fetch the listens from the correct payload field
- if (data && data.payload && data.payload.listens) {
- displayListens(data.payload.listens);
- addButton.style.display = 'block'; // Show 'Add to Playlist' button once listens are displayed
- } else {
- throw new Error('No listens found or incorrect response structure.');
- }
- } catch (error) {
- // Display the error message on the page
- debugContainer.innerHTML += `<p>Error: ${error.message}</p>`;
- console.error('Error:', error);
- }
- }
- // Function to display listens in the UI
- function displayListens(listens) {
- listensContainer.innerHTML = ''; // Clear previous listens
- if (listens.length === 0) {
- listensContainer.innerHTML = '<p>No listens found for this user.</p>';
- return;
- }
- listens.forEach((listen, index) => {
- const trackMetadata = listen.track_metadata;
- const recordingMbid = trackMetadata.mbid_mapping ? trackMetadata.mbid_mapping.recording_mbid : null;
- const artistName = trackMetadata.artist_name;
- const trackName = trackMetadata.track_name;
- const listenItem = document.createElement('div');
- listenItem.classList.add('listen-item');
- listenItem.innerHTML = `
- <input type="checkbox" id="listen-${index}" value="${recordingMbid}">
- <label for="listen-${index}">${trackName} by ${artistName}</label>
- `;
- listensContainer.appendChild(listenItem);
- });
- }
- // Function to add selected listens to playlist
- async function addToPlaylist() {
- const selectedListens = [];
- const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
- checkboxes.forEach((checkbox) => {
- selectedListens.push(checkbox.value); // Grab the recording MBID
- });
- if (selectedListens.length > 0) {
- console.log("Selected listens:", selectedListens); // Log the selected listens for debugging
- await sendToPlaylist(selectedListens);
- } else {
- alert('No listens selected!');
- }
- }
- // Function to send selected listens to the playlist
- async function sendToPlaylist(selectedListens) {
- const playlistMbid = '191af5d4-4d57-4ed1-ac03-e31badff7cd2'; // Your provided playlist MBID
- try {
- const response = await fetch(`https://api.listenbrainz.org/1/playlist/${playlistMbid}/item-add`, {
- method: 'POST',
- headers: {
- 'Authorization': `Token ${listenBrainzToken}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- recording_mbid: selectedListens
- })
- });
- if (response.ok) {
- alert('Successfully added to playlist!');
- } else {
- const responseText = await response.text(); // Get the error text if available
- console.error("Response Error Text:", responseText); // Log the error text
- throw new Error(`Failed to add to playlist: ${response.status} - ${responseText}`);
- }
- } catch (error) {
- alert(`Error: ${error.message}`);
- console.error('Error:', error);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment