Files
  • index.js
  • public
  • views
  • LICENSE.txt
  • package-lock.json
  • package.json
  • shrinkwrap.yaml
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
1// server.js
// where your node app starts

// init project
var express = require('express');

var app = express();
var mustacheExpress = require('mustache-express');
app.engine('mustache', mustacheExpress());
app.set('view engine', 'mustache');

// https


// init Spotify API wrapper
var SpotifyWebApi = require('spotify-web-api-node');
var redirectUri = 'https://wordless.4ty2.fun/callback';
var tokenExpirationEpoch;
var spotifyApi = new SpotifyWebApi({
  clientId : process.env.CLIENT_ID,
  clientSecret : process.env.CLIENT_SECRET,
  redirectUri : redirectUri
});



// Youtube search
const axios = require('axios');


// DB
var jsonstore = require('jsonstore.io')
let store = new jsonstore(process.env.DB)

// Prototype functions
String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};


app.use(express.static('public'));

// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function (request, response) {
  response.sendFile(__dirname + '/views/index.html');
});

app.get("/license", function (request, response) {
  response.sendFile(__dirname + '/LICENSE.txt');
});

app.get("/authorize", function (request, response) {
  var scopesArray = request.query.scopes.split(',');
  var authorizeURL = spotifyApi.createAuthorizeURL(scopesArray);
  console.log(authorizeURL)
  response.send(authorizeURL);
});

// Exchange Authorization Code for an Access Token
app.get("/callback", function (request, response) {
  var authorizationCode = request.query.code;
  
  // Check folks haven't just gone direct to the callback URL
  if (!authorizationCode) {
    response.redirect('/');
  } else {
    response.redirect("/playlists")
  }
  
  spotifyApi.authorizationCodeGrant(authorizationCode)
  .then(function(data) {

    // Set the access token and refresh token
    spotifyApi.setAccessToken(data.body['access_token']);
    spotifyApi.setRefreshToken(data.body['refresh_token']);

    // Save the amount of seconds until the access token expired
    tokenExpirationEpoch = (new Date().getTime() / 1000) + data.body['expires_in'];
  }, function(err) {
    console.log('Something went wrong when retrieving the access token!', err.message);
  });
});


// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
});



// LOGIC 👇

function playlistData(id, playlist, res){
  spotifyApi.getPlaylist(id, playlist)
    .then(function(data) {
			store.read(playlist).then( (stuff) => {
				console.log(stuff)
				if(stuff==null){
					console.log(`new`)
					makeInstrumental(data.body);
					return res.render("wait", {"id": data.body.id})
				}
				else{
					console.log(`exists`)
					res.redirect(`/play/${playlist}`)
				}
			})
      
      
    }, function(err) {
      console.log('Something went wrong!', err);
    });
}

function getPlaylists(id, res){
  spotifyApi.getUserPlaylists(id)
    .then(function(data) {
      var playlists = data.body.items;
      var list = `<ul>`;
      for(var i = 0; i<playlists.length; i++){
        var playlist = playlists[i]
				list+=`<div class="row track" onclick="window.location = '/playlists/${id}/${playlist.id}'"><img class="col-4 is-left track-image" src="${playlist.images[0].url}" style="display:block; margin:auto"><span class="col-8 track-name is-center">${playlist.name}</span></div>`
      }
      res.render("playlists", {"list": list});
    },function(err) {
      console.log('Something went wrong!', err);
  });
}

app.get("/playlists", function (request, response) {
spotifyApi.getMe()
  .then(function(data) {
    getPlaylists(data.body.id, response);
  }, function(err) {
    console.log('Something went wrong!', err);
  });
});

app.get("/playlists/:user/:id", function (request, response) {
  playlistData(request.params.user, request.params.id, response)
});

app.get("/play/:id", function (request, response) {
  store.read(request.params.id).then( (data) => {
		var tracks = []
    for (var key in data) {
      if (data.hasOwnProperty(key) && key!="info") {
					tracks.push([decodeURIComponent(key), data[key].id, data[key].image])
      }
    }
    return response.render("play", {"name": data.info.name, "url": data.info.url, "tracks": JSON.stringify(tracks), "image": data.info.image, "id": request.params.id})
  })
});

function getInstrumental(track, artist, id, image){
	var token = process.env.PR;
	var query = `${artist} ${track}`
	console.log(query)
	var url = `https://www.youtube.com/results?search_query=${query} instrumental`;
	axios.get(`https://page.rest/fetch?token=${token}&url=${url}&selector=.yt-uix-tile-link`)
  .then(function (response) {
		var trackO = response.data["selectors"][".yt-uix-tile-link"][0];
		if(trackO.text.toLowerCase().search("instrumental")== -1 && trackO.text.toLowerCase().search("beat")== -1){
			trackO = response.data["selectors"][".yt-uix-tile-link"][1];
			if(trackO.text.toLowerCase().search("instrumental")== -1 && trackO.text.toLowerCase().search("beat")== -1){
				return;
			}	
		}
		
		var fin = {
			"id": trackO.attrs.href.slice(9),
			"image": image
		}
    console.log(`Done - ${track} - ${fin.id}`);
		store.write(`${id}/${track}`, fin)
  })	
	.catch(function (error) {
    console.log(error);
  })
}

function makeInstrumental(playlist){
  var tracks = playlist.tracks.items;
  var id = playlist.id;
  var instrumentals = [];
	var count = 0;
	console.log(id)
  store.write(`${id}/info`,{"name": playlist.name, "url": playlist.external_urls.spotify, "image": playlist.images[0].url})
  var labour = setInterval(function(){
			if(tracks[count].track.popularity>30){
				console.log(tracks[count].track)
				getInstrumental(tracks[count].track.name, tracks[count].track.artists[0].name, id, tracks[count].track.album.images[1].url)
				console.log(count)
			}
			if((count+1)==tracks.length){
				console.log(`clearing`)
				clearInterval(labour)
			}
			count++;
		}, 100);

}


node v10.15.2 linux/amd64