-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
144 lines (118 loc) · 3.59 KB
/
Copy pathindex.js
File metadata and controls
144 lines (118 loc) · 3.59 KB
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
import 'dotenv/config';
import fetch from 'node-fetch';
import express from 'express';
import puppeteer from "puppeteer";
const app = express();
const PORT = process.env.PORT || 8080;
app.use(express.static('public'));
let cachedAccessToken = null;
let tokenExpiresAt = 0;
function accessTokenStillValid() {
return cachedAccessToken && Date.now() < tokenExpiresAt;
}
function cacheToken(token, expiresInSeconds) {
cachedAccessToken = token;
tokenExpiresAt = Date.now() + (expiresInSeconds - 60) * 1000;
}
async function fetchWebApi(endpoint, method, body, token) {
const res = await fetch(`https://api.spotify.com/${endpoint}`, {
headers: {
Authorization: `Bearer ${token}`,
},
method,
body:JSON.stringify(body)
});
return await res.json();
}
async function getTopArtists(token){
return (await fetchWebApi(
'v1/me/top/artists?time_range=short_term&limit=3', 'GET', undefined, token
)).items;
}
async function getTopTracks(token) {
return (
await fetchWebApi(
"v1/me/top/tracks?time_range=short_term&limit=5",
"GET",
undefined,
token
)
).items;
}
async function getAccessToken() {
if (accessTokenStillValid()) {
console.log('Using cached access token');
return cachedAccessToken;
}
console.log('Refreshing access token');
const credentials = Buffer.from(
`${process.env.SPOTIFY_CLIENT_ID}:${process.env.SPOTIFY_CLIENT_SECRET}`
).toString('base64');
const res = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
Authorization: `Basic ${credentials}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: process.env.SPOTIFY_REFRESH_TOKEN
})
});
if (!res.ok) {
const errorText = await res.text();
throw new Error(`Token refresh failed: ${errorText}`);
}
const data = await res.json();
cacheToken(data.access_token, data.expires_in);
return data.access_token;
}
app.get("/api/top-artists", async (req, res) => {
try {
const token = await getAccessToken();
console.log("Access token acquired");
const artists = await getTopArtists(token);
res.json(artists);
} catch (err) {
console.error(err);
res.status(500).json({ error: "Failed to fetch top artists" });
}
});
app.get("/api/top-tracks", async (req, res) => {
try {
const token = await getAccessToken();
console.log("Access token acquired");
const tracks = await getTopTracks(token);
res.json(tracks);
} catch (err) {
console.error(err);
res.status(500).json({ error: "Failed to fetch top artists" });
}
});
app.get("/api/refresh-ui", async (req, res) => {
try {
await captureUIScreenshot();
res.json({ success: true, message: "UI update triggered" });
} catch (err) {
res.status(500).json({ error: "UI update failed" });
}
});
async function captureUIScreenshot() {
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"],
executablePath: '/usr/bin/chromium'
});
const page = await browser.newPage();
await page.setViewport({ width: 480, height: 800 });
await page.goto(`http://localhost:${PORT}`, { waitUntil: "networkidle0" });
await page.waitForSelector(".artist-card", { timeout: 5000 }).catch(() => {
console.log("Cards didn't load in time, taking screenshot anyway...");
});
await page.screenshot({ path: "screenshot.png" });
await browser.close();
console.log("Screenshot saved.");
}
// Start server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});