-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
181 lines (178 loc) · 6.31 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
const rand = Math.floor(Math.random() * 2)
const promts = ['How do you feel?', 'What are you thinking?']
document.getElementById('mood').placeholder = promts[rand]
document.getElementById('music').addEventListener('click', async function(e) {
e.preventDefault();
const mood = document.getElementById('mood').value
const selector = document.getElementById('language')
let language = selector.options[selector.selectedIndex].text
if (language == 'Random') {
language = selector.options[Math.floor(Math.random() * 14) + 1].text
}
if (mood != '') {
try {
const response = await fetch('api/server', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ mood, language }),
})
const info = await response.json()
const clientId = info.clientId;
const clientSecret = info.clientSecret;
const text = info.response.replace('"', '').replace('.','')
console.log(text)
const trackUri = await getMusicForMood(text, clientId, clientSecret);
playMusic(trackUri);
} catch (error) {
console.error('Error text:', error);
}
}
else{
document.getElementById('mood').placeholder = 'Give me a promt'
const shakeAnim = [
{ transform: "translateX(0)" },
{ transform: "translateX(-5px)" },
{ transform: "translateX(5px)" },
{ transform: "translateX(-5px)" },
{ transform: "translateX(0)" },
];
const shakeTiming = {
duration: 250,
iterations: 2,
};
document.getElementById('mood').animate(shakeAnim,shakeTiming)
}
});
document.getElementById('playlist').addEventListener('click', async function(e) {
e.preventDefault();
const mood = document.getElementById('mood').value
const selector = document.getElementById('language')
let language = selector.options[selector.selectedIndex].text
if (language == 'Random') {
language = selector.options[Math.floor(Math.random() * 14) + 1].text
}
if (mood != '') {
document.getElementById('mood').placeholder = promts[rand]
try {
const response = await fetch('api/server', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ mood, language}),
})
const info = await response.json()
const clientId = info.clientId;
const clientSecret = info.clientSecret;
const text = info.response.replace('"', '').replace('.','')
console.log(text)
const trackUri = await getPlaylistForMood(text, clientId, clientSecret);
playMusic(trackUri);
} catch (error) {
console.error('Error text:', error);
}
}
else{
document.getElementById('mood').placeholder = 'Give me a promt'
const shakeAnim = [
{ transform: "translateX(0)" },
{ transform: "translateX(-5px)" },
{ transform: "translateX(5px)" },
{ transform: "translateX(-5px)" },
{ transform: "translateX(0)" },
];
const shakeTiming = {
duration: 250,
iterations: 2,
};
document.getElementById('mood').animate(shakeAnim,shakeTiming)
}
});
async function getMusicForMood(mood, CLIENT_ID, CLIENTSECRET) {
const clientId = CLIENT_ID;
const clientSecret = CLIENTSECRET;
const tokenResponse = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa(clientId + ':' + clientSecret)
},
body: 'grant_type=client_credentials'
});
const tokenData = await tokenResponse.json();
const accessToken = tokenData.access_token;
const query = `${mood}`;
const response = await fetch(`https://api.spotify.com/v1/search?q=${encodeURIComponent(query)}&type=track&limit=25`, {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
const data = await response.json();
const i = Math.floor(Math.random() * 25)
const albumCoverUrl = data.tracks.items[i].album.images[0].url
console.log(data)
setAlbumCoverColor(albumCoverUrl)
return data.tracks.items[i].uri;
};
async function getPlaylistForMood(mood, CLIENT_ID, CLIENTSECRET) {
const clientId = CLIENT_ID;
const clientSecret = CLIENTSECRET;
const moods = mood
const tokenResponse = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa(clientId + ':' + clientSecret)
},
body: 'grant_type=client_credentials'
});
const tokenData = await tokenResponse.json();
const accessToken = tokenData.access_token;
const query = `${mood}`;
const response = await fetch(`https://api.spotify.com/v1/search?q=${encodeURIComponent(query)}&type=playlist&limit=10`, {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
const data = await response.json();
const i = Math.floor(Math.random() * 10)
try {
const albumCoverUrl = data.playlists.items[i].images[0].url
console.log(data)
setAlbumCoverColor(albumCoverUrl)
} catch (error) {
console.log(error)
}
return data.playlists.items[i].uri;
};
async function playMusic(trackUri) {
const element = document.getElementById('embed-iframe');
const options = {
uri: trackUri,
theme: 'dark'
};
if (!window.embedController) {
window.onSpotifyIframeApiReady = (IFrameAPI) => {
IFrameAPI.createController(element, options, (EmbedController) => {
window.embedController = EmbedController;
EmbedController.play()
console.log(element)
});
};
} else {
window.embedController.loadUri(trackUri);
window.embedController.play()
}
};
function setAlbumCoverColor(albumCoverUrl) {
const img = new Image();
img.crossOrigin = "Anonymous";
img.src = albumCoverUrl;
img.onload = function() {
const colorThief = new ColorThief();
const color = colorThief.getColor(img);
document.body.style.backgroundColor = `rgb(${color[0]}, ${color[1]}, ${color[2]})`;
};
};