-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
193 lines (174 loc) · 6.98 KB
/
server.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
/*jshint esversion: 8 */
//Place your token in accesstoken.txt
//Creates a cache to bypass the scraper if song has been previously searched
const ACCESS_TOKEN_FILE = 'accesstoken.txt';
const LYRIC_CACHE_FILE = './lyric_cache.db';
var http = require('http');
var url = require("url");
var fs = require('fs');
var querystring = require('querystring');
const api = require('genius-api');
var cheerio = require('cheerio');
var axios = require('axios');
var path = require('path');
var genius;
var accessToken;
const port = 8081;
var Datastore = require('nedb-promises');
var cachefile = Datastore.create(LYRIC_CACHE_FILE);
var requests_served = 0;
var FAVICON = path.join(__dirname, 'public', 'favicon.ico');
const buttonHtml = `
<script>document.getElementById('clicky').onclick = function(){
var queryvalue = document.getElementById('fieldy').value;
window.location= window.location.href.split('?')[0] + '?action=search&name=' + queryvalue;
}
document.getElementById('fieldy').addEventListener("keyup", function (event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("clicky").click();
}
});
document.getElementById('fieldy').value = '';
</script>
`;
const searchBarHtml = `
<p style="display:inline" ></p><input type="text" name="fname" id ="fieldy" autofocus>
<button id="clicky">Search</button>
`;
fs.readFile(ACCESS_TOKEN_FILE, function (err, buff) {
if (err){console.log(err);}
accessToken = buff;
genius = new api(accessToken);
});
async function getData(artist_name) {
try {
return await genius.search(artist_name);
}
catch (error) {
return await error;
}
}
function parseSongHTML(htmltext,urlscrape)
{
var lyrics;
var body;
body = cheerio.load(htmltext);
lyrics = body('.lyrics').text().substring(37);
var dbpayload = {
saved_url: urlscrape,
lyric_body: lyrics,
};
cachefile.insert(dbpayload, function (err, newDoc) {});
return lyrics;
}
async function scrapeLyrics(url) {
var result = await axios.get(url);
return parseSongHTML(result.data,url);
}
var instructionsNewVisitor = function (req, res) {
var params = querystring.parse(url.parse(req.url).query); //parses params
var urlscrape = '';
var pathname = url.parse(req.url).pathname;
if (req.method === 'GET' && pathname === '/favicon.ico') {
// MIME type of your favicon.
//
// .ico = 'image/x-icon' or 'image/vnd.microsoft.icon'
// .png = 'image/png'
// .jpg = 'image/jpeg'
// .jpeg = 'image/jpeg'
res.setHeader('Content-Type', 'image/x-icon');
// Serve your favicon and finish response.
//
// You don't need to call `.end()` yourself because
// `pipe` will do it automatically.
fs.createReadStream(FAVICON).pipe(res);
return;
}
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8"
});
if ('action' in params) {
//Returns the lyrics for the top result of the search query
if (params.action == "search") {
console.log('');
res.write('<head><link rel="shortcut icon" type="image/png" href="/favicon.ico"/><title>Lyrica - The world\'s most lightweight Lyric Finder</title ></head>');
searchquery: try{
var songtitle = '';
var songarray = [];
if (params.name == ''){
res.write('<h3 style="font-family:Verdana;">Please Enter a Search Term...</h3><hr>');
res.write(searchBarHtml);
res.write(buttonHtml);
res.end();
console.log('No search term Received');
break searchquery;
}
console.log("Request Received: " + params.name);
console.log("Waiting for Genius API...");
getData(params.name)
.then(data => {
if (data.hits.length == 0){
throw new Error('No Results Found');
}
urlscrape = data.hits[0].result.url;
console.log("URL Found: " + urlscrape);
return urlscrape;
})
.then(saurl => {
return cachefile.find({
saved_url: saurl
})
;})
.then(docs =>{
if (docs.length > 0) {
console.log('Found in Cache!');
return docs[0].lyric_body;
} else {
console.log('Waiting for Genius Site...');
return scrapeLyrics(urlscrape);
}
})
.then(finalresult => {
songarray = urlscrape.substring(19).split('-');
for (let i = 0; i<songarray.length-1; i++){
songtitle += songarray[i].charAt(0).toUpperCase() + songarray[i].slice(1) + " ";
}
res.write('<body><h3 style="font-family:Verdana;display:inline" >' + songtitle + '</h3>');
res.write(' ' + searchBarHtml);
res.write(buttonHtml);
res.write('<hr>');
res.write('<p style="font-family:Verdana;">' + finalresult.replace(/[\n\r]/g, '<br>').replace(/\[/g, '<b>[').replace(/\]/g, ']</b>'));
requests_served++;
res.write("<hr> Made Possible by the Genius API <br> Served total of: " + requests_served.toString() + " requests since last restart </p>");
res.end('</body>');
console.log('Request Served: ' + requests_served);
console.log('');
})
.catch(e => {
res.write('<h3 style="font-family:Verdana;">(Surprisingly) No Results Found!</h3><hr>');
res.write(searchBarHtml);
res.write(buttonHtml);
res.end();
console.log(e);
console.log('(Surprisingly) No Results Found!');
});
}
catch(err){
console.log(err);
}
}
else if (params.action == "wake")
{
console.log("Server Awoken");
res.end();
}
//Todo: Search for Album, and grabs all songs on it.
}
};
var server = http.createServer(instructionsNewVisitor);
server.listen(process.env.PORT || port);
console.log("Listening on Port " + (process.env.PORT || port));