keolis-services
Version:
Keolis services includes Microphone, Location, Voice Activity Detector, Heart rate through web bluetooth API, text to speech, stop watch with our own cloud.
199 lines (161 loc) • 6.54 kB
JavaScript
const { spotifyApi } = require('../variables/constants');
const $ = require('jquery');
$(window).on('load', function() {
onPageLoad();
});
// Authorize spotify with username and password
export const spotify_authorize = ({clientId, secretKey, redirect_uri}) => {
try {
if (!clientId || !secretKey || !redirect_uri) return false;
global.clientId = clientId;
global.secretKey = secretKey;
global.redirect_uri = redirect_uri;
let spotifyAuthUrl = spotifyApi;
spotifyAuthUrl += 'authorize?&response_type=code';
spotifyAuthUrl += '&client_id=' + global.clientId;
spotifyAuthUrl += '&scope=user-read-currently-playing user-read-private user-read-email user-modify-playback-state user-top-read playlist-modify-public playlist-modify-private user-read-playback-position user-library-read';
spotifyAuthUrl += '&redirect_uri=' + encodeURI(global.redirect_uri);
window.location.href = spotifyAuthUrl;
} catch (error) {
console.log(error);
return false;
}
}
// Page load
const onPageLoad = () => {
if (window.location.search.length > 0) {
handleRedirect();
}
}
// Get code from redirected url
const getCode = () => {
let code = null;
const queryString = window.location.search;
if (queryString.length > 0) {
const urlParams = new URLSearchParams(queryString);
code = urlParams.get('code');
}
return code;
}
// Handle redirect when it gets code
const handleRedirect = () => {
let code = getCode();
fetchAccessToken(code);
window.history.pushState("", "", global.redirect_uri);
}
// Get Access Token and Refresh Token with code
const fetchAccessToken = (code) => {
let body = 'grant_type=authorization_code';
body += '&code=' + code;
body += '&redirect_uri=' + encodeURI(global.redirect_uri);
body += '&client_id=' + global.clientId;
body += '&client_secret=' + global.secretKey;
callAuthorizationApi(body);
}
// Call spotify authorization api
const callAuthorizationApi = (body) => {
let xhr = new XMLHttpRequest();
xhr.open("POST", spotifyApi + 'api/token', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(global.clientId + ':' + global.secretKey));
xhr.send(body);
xhr.onload = handleAuthorizationResponse;
}
// Handle spotify authorization api response
const handleAuthorizationResponse = () => {
if (this.status == 200) {
let data = JSON.parse(this.responseText);
if (data.access_token != undefined) {
localStorage.setItem('access_token', data.access_token);
}
if (data.refresh_token != undefined) {
localStorage.setItem('refresh_token', data.refresh_token);
}
GetCurrentSpotifyUser();
// onPageLoad();
return { success: true }
} else {
return { success: false, message: "Failed to login to Spoitfy. Please try again." }
}
}
export const GetCurrentSpotifyUser = () => {
if (localStorage.getItem('access_token')) return false;
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.addEventListener("readystatechange", function() {
if (this.readyState === 4) {
let data = JSON.parse(this.responseText);
localStorage.setItem('spotify_userid', data.id);
CreatePlaylistID();
getTop10UserSongs();
}
});
xhr.open("GET", "https://api.spotify.com/v1/me");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + localStorage.getItem('access_token'));
xhr.send();
}
/*
playlistData object
{
"name": string,
"description": string,
"public": boolean
}
*/
const CreatePlaylistID = (playlistData) => {
if (localStorage.getItem('access_token')) return false;
var data = JSON.stringify({
"name": playlistData.name,
"description": playlistData.description,
"public": playlistData.public
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.addEventListener("readystatechange", function() {
if (this.readyState === 4) {
let data = JSON.parse(this.responseText);
localStorage.setItem('spotify_playlistid', data.id);
return { success: true, playlistLink: "https://open.spotify.com/playlist/" + data.id }
}
});
xhr.open("POST", "https://api.spotify.com/v1/users/" + localStorage.getItem('spotify_userid') + "/playlists");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + localStorage.getItem('access_token'));
xhr.send(data);
}
const getTop10UserSongs = () => {
if (localStorage.getItem('access_token')) return false;
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.addEventListener("readystatechange", function() {
if (this.readyState === 4) {
let data = JSON.parse(this.responseText);
var songs = [];
data.items.forEach(element => {
songs.push(element.uri);
});
localStorage.setItem('spotify_top10songs', songs);
return { success: true, songs: songs }
}
});
xhr.open("GET", "https://api.spotify.com/v1/me/top/tracks?limit=10");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + localStorage.getItem('access_token'));
xhr.send();
}
export const getCurrentPlayingSong = () => {
if (localStorage.getItem('access_token')) return false;
var request = new XMLHttpRequest();
request.open('GET', "https://api.spotify.com/v1/me/player/currently-playing", false); // `false` makes the request synchronous
request.setRequestHeader("Content-Type", "application/json");
request.setRequestHeader("Authorization", "Bearer " + localStorage.getItem('access_token'));
request.send(null);
if (request.status === 200) {
if (request.responseText) {
let data = JSON.parse(request.responseText);
return data.item.uri || "";
}
}
return "";
}