Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filips testbranch #9

Merged
merged 4 commits into from
Dec 2, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 62 additions & 37 deletions client/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,14 @@ const clientSecret = '6f2f0a36046f4f21980873a48c7bdab0';

// API dialogue functions

async function getToken() {
function getRandomIntInclusive(min, max) {
const newMin = Math.ceil(min);
const newMax = Math.floor(max);
return Math.floor(Math.random() * (newMax - newMin + 1) + newMin); // The maximum is inclusive and the minimum is inclusive
}

async function getToken() {
// Gets authorisation token
const result = await fetch('https://accounts.spotify.com/api/token',{
method: 'POST',
headers: {
Expand All @@ -21,7 +27,7 @@ async function getToken() {
}

async function getGenres(token) {

// Gets a list of genres
const result = await fetch(`https://api.spotify.com/v1/browse/categories?locale=sv_US&limit=40`, {
method: 'GET',
headers: { 'Authorization' : 'Bearer ' + token}
Expand All @@ -32,7 +38,7 @@ async function getGenres(token) {
}

async function getPlaylistsByGenre(token, genreId, limit) {

//Based on genre ID gets a list of playlists of that genre
const result = await fetch(`https://api.spotify.com/v1/browse/categories/${genreId}/playlists?limit=${limit}`, {
method: 'GET',
headers: { 'Authorization' : 'Bearer ' + token}
Expand All @@ -45,10 +51,8 @@ async function getPlaylistsByGenre(token, genreId, limit) {

}

async function getTracks(token, tracksEndPoint) {

const limit = "10";

async function getTracks(token, tracksEndPoint, limit) {
//Based on a playlist gets a list of songs from that playlist
const result = await fetch(`${tracksEndPoint}?limit=${limit}`, {
method: 'GET',
headers: { 'Authorization' : 'Bearer ' + token}
Expand All @@ -58,39 +62,37 @@ async function getTracks(token, tracksEndPoint) {
return data;
}

async function getTrack(token, tracksEndPoint) {

const result = await fetch(`${tracksEndPoint}`, {
method: 'GET',
headers: {'Authorization' : 'Bearer ' + token}
});

const data = result.json();
return data;
}

async function initSongs(){
const listOfTracks = [];
const token = await getToken();
// A function that gets us a lot of songs from different genres on spotify
const listOfTracks = []; //Initialize output
const token = await getToken(); //Get token
console.log(token)
const genres = await getGenres(token)
let prom = new Promise((resolve, reject) => {
genres.forEach(async (genre, index, array) => {
//console.log(`Getting tracks from: ${genre.name} has id: ${genre.id}`)
let prom = new Promise((resolve, reject) => { //Wrapped the loop in a promise to make the rest of the func wait for the loop to execute

genres.map(async (genre, index, array) => {

console.log(`Getting tracks from: ${genre.name} has id: ${genre.id}`)
const playlists = await getPlaylistsByGenre(token, genre.id, 3)

if(typeof playlists !== "undefined"){
playlists.forEach(async playlist =>{

playlists.map(async playlist =>{

//console.log(playlist.href);
if(playlist !== null){
const plEndpoint = `${playlist.href}/tracks`
const tracks = await getTracks(token, plEndpoint);
const tracks = await getTracks(token, plEndpoint,10);
tracks.items.map(obj => ({ ...obj, gen: genre.name }))
listOfTracks.push(...tracks.items)
console.log(listOfTracks.length)
//console.log(tracks.items)
console.log(listOfTracks)
}
})
}
if (index === array.length -1) resolve();
}
if (index === array.length -1) {
resolve()
};
});
});

Expand All @@ -100,27 +102,49 @@ async function initSongs(){
console.log(listOfTracks.length);
});

//This is a placeholder part until I make all of the above work.
const plalylistSg = "https://api.spotify.com/v1/playlists/37i9dQZF1DXcF6B6QPhFDv/tracks"
const tracks = await getTracks(token, plalylistSg);
return tracks.items
const tracks = await getTracks(token, plalylistSg, 60);
console.log(tracks)
return tracks.items.map(obj => ({ ...obj, gen: "Rock"}))
}



async function songNamesArray(){
const songs = await initSongs();
let files = ['a', 'b', 'c', 'd', 'e', 'f'];

console.log(songs)
const array = [];
songs.forEach(element => {
array.push({
name : element.track.name,
link : element.track.external_urls.spotify
link : element.track.external_urls.spotify,
image_url : element.track.album.images[0].url,
genre : element.gen
})
})
return(array)
//console.log(array)
}


// UI Handling
// -------------------UI Handling-------------------

//Get random 10 items from an aray (to be replacedby betterselection item)
function getRandomTen(list) {
console.log('fired get 10 songs');
const range = [...Array(10).keys()];
const newArray = range.map(() => {
const index = getRandomIntInclusive(0, list.length);
let picked = list[index];
return picked;
});
return newArray;
}

// Inject a song to the page
function injectHTML(list) {
console.log('fired injectHTML');
const target = document.querySelector('#music_list');
Expand All @@ -135,18 +159,19 @@ function injectHTML(list) {
});
}


// Turn the site script on
async function init(){
const submit = document.querySelector('#submit');

document.getElementById("music_list").style.display = "none";
const submit = document.querySelector('#submit');

let songArray = await songNamesArray();
submit.addEventListener('click', (e) => {
e.preventDefault();
injectHTML(songArray);
console.log(songArray);
sample = getRandomTen(songArray)
injectHTML(sample)
console.log(sample);
document.getElementById("music_list").style.display = "block";

})

}
Expand Down