Skip to content

Instantly share code, notes, and snippets.

@williamtdr
Created December 13, 2017 01:22
Show Gist options
  • Save williamtdr/8f631d9c796ed14dafd32f5fca5cdf18 to your computer and use it in GitHub Desktop.
Save williamtdr/8f631d9c796ed14dafd32f5fca5cdf18 to your computer and use it in GitHub Desktop.
Activates a spotify connect device at a given time, and plays a random song from a playlist with gradually increasing volume. Customize as desired :)
const SpotifyWebApi = require('spotify-web-api-node');
const WebApiRequest = require('./node_modules/spotify-web-api-node/src/webapi-request');
const HttpManager = require('./node_modules/spotify-web-api-node/src/http-manager');
const express = require('express');
const bodyParser = require('body-parser');
const open = require('open');
const fs = require('fs');
const moment = require('moment-timezone');
let app = express();
app.use(bodyParser.json());
app.get('/callback', function(req, res) {
spotifyApi.authorizationCodeGrant(code)
.then(async function(data) {
console.log('The token expires in ' + data.body['expires_in']);
console.log('The access token is ' + data.body['access_token']);
console.log('The refresh token is ' + data.body['refresh_token']);
fs.writeFileSync('credentials.json', JSON.stringify({
access_token: data.body['access_token'],
refresh_token: data.body['refresh_token']
}));
// Set the access token on the API object to use it in later calls
spotifyApi.setAccessToken(data.body['access_token']);
spotifyApi.setRefreshToken(data.body['refresh_token']);
await arm();
}, function(err) {
console.log('Something went wrong!', err);
});
res.json({
status: "OK"
});
});
app.listen(5000, 'localhost', function() {
console.log('Web server listening on port 5000');
});
const spotifyApi = new SpotifyWebApi({
clientId : 'client id goes here',
clientSecret : 'client secret goes here',
redirectUri : 'http://localhost:5000/callback'
});
function setupCredentials() {
try {
const c = JSON.parse(fs.readFileSync('credentials.json'));
spotifyApi.setAccessToken(c.access_token);
spotifyApi.setRefreshToken(c.refresh_token);
arm();
} catch(e) {
open(spotifyApi.createAuthorizeURL(['playlist-read-private', 'user-read-currently-playing', 'user-modify-playback-state', 'user-read-playback-state']));
}
}
async function getAlexa() {
return new Promise(async (resolve, reject) => {
const devices = await spotifyApi.getMyDevices();
const device = devices.body.devices.find(device => device.type !== "Computer");
if(!device)
return reject();
resolve(device);
});
}
async function switchDevices(alexaId) {
return spotifyApi.transferMyPlayback({
deviceIds: [ alexaId ],
play: false
});
}
async function setVolume(volumePercent) {
const request = WebApiRequest.builder()
.withPath('/v1/me/player/volume')
.withHeaders({ 'Content-Type' : 'application/json' })
.withQueryParameters({
'volume_percent': volumePercent
})
.build();
spotifyApi._addAccessToken(request, spotifyApi.getAccessToken());
spotifyApi._addBodyParameters(request, {});
return spotifyApi._performRequest(HttpManager.put, request);
}
async function setShuffle(doShuffle) {
return spotifyApi.setShuffle({
state: doShuffle
});
}
async function playAlarm(pl) {
spotifyApi.play({
context_uri: "spotify:user:williamtdr:playlist:2w0q41q66yYiQSkgI6e1Qu",
offset: { "position": pl }
})
}
async function isPlaying() {
return new Promise(async (resolve, reject) => {
let ti = await spotifyApi.getMyCurrentPlayingTrack();
ti = ti.body;
resolve(ti.is_playing);
});
}
async function getPlaylistLength() {
return new Promise(async (resolve, reject) => {
let playlist = await spotifyApi.getPlaylist('williamtdr', '2w0q41q66yYiQSkgI6e1Qu');
playlist = playlist.body;
resolve(playlist.tracks.total);
});
}
async function fireAlarm() {
const alexa = await getAlexa();
const alexaId = alexa.id;
try {
console.log("TIME TO WAKE UP!!!!!!");
await switchDevices(alexaId);
await setShuffle(true);
let pl = await getPlaylistLength();
await setVolume(10);
await playAlarm(Math.random() * (pl - 1) + 1);
function gradualWakeup(i) {
setTimeout(async function() {
const playing = await isPlaying();
const newVolume = 10 + (i * 5);
if(playing) {
console.log(`Set volume to ${newVolume}.`);
await setVolume(newVolume);
}
}, 10000 * i);
}
for(let i = 1; i < 4; i++)
gradualWakeup(i);
} catch(e) {
console.log(e);
}
return new Promise((resolve) => {
resolve();
});
}
async function isItTime() {
const a = moment.tz("America/Chicago");
if(a.hour() === 8 && a.minute() === 0) {
fireAlarm();
setTimeout(isItTime, 2 * 60 * 1000);
return;
}
setTimeout(isItTime, 3000);
delete a;
}
async function arm() {
console.log("Logged in, ready to go!");
setTimeout(isItTime, 1000);
}
setupCredentials();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment