veltrixcode commited on
Commit
22a2b25
·
verified ·
1 Parent(s): 313b624

Upload 14 files

Browse files
controllers/lyricsController.js ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { getLyrics } from '../services/spotifyLyricsService.js';
2
+ import { searchSpotifyGraphQL } from '../services/browserAuthService.js';
3
+
4
+ const normalizeText = (text) => {
5
+ if (!text) return '';
6
+ return text.toLowerCase()
7
+ .replace(/[^a-z0-9]/g, ' ')
8
+ .replace(/\s+/g, ' ')
9
+ .trim();
10
+ };
11
+
12
+ const parseArtistNames = (artistStr) => {
13
+ if (!artistStr) return [];
14
+ // Split on comma, ampersand, or " and "
15
+ return artistStr
16
+ .split(/,|\s+and\s+|\s+&\s+/i)
17
+ .map(name => normalizeText(name))
18
+ .filter(name => name.length > 0);
19
+ };
20
+
21
+ const findBestMatch = (candidates, name, artistQuery, duration) => {
22
+ const targetName = normalizeText(name);
23
+ const targetArtists = parseArtistNames(artistQuery);
24
+
25
+ let targetDurationMs = null;
26
+ if (duration !== undefined && duration !== null) {
27
+ const parsedDuration = parseFloat(duration);
28
+ if (!isNaN(parsedDuration)) {
29
+ targetDurationMs = parsedDuration < 3000 ? parsedDuration * 1000 : parsedDuration;
30
+ }
31
+ }
32
+
33
+ let bestMatch = null;
34
+ let bestScore = -1;
35
+
36
+ for (const track of candidates) {
37
+ let score = 0;
38
+ const trackName = normalizeText(track.name);
39
+
40
+ if (trackName === targetName) {
41
+ score += 40;
42
+ } else if (trackName.includes(targetName) || targetName.includes(trackName)) {
43
+ score += 20;
44
+ }
45
+
46
+ // Artist scoring
47
+ const trackArtists = (track.artists || []).map(a => normalizeText(a.name));
48
+ let matchedArtistsCount = 0;
49
+ for (const targetArtist of targetArtists) {
50
+ if (trackArtists.some(ta => ta === targetArtist || ta.includes(targetArtist) || targetArtist.includes(ta))) {
51
+ matchedArtistsCount++;
52
+ }
53
+ }
54
+
55
+ if (targetArtists.length > 0) {
56
+ if (matchedArtistsCount === targetArtists.length) {
57
+ score += 40;
58
+ } else if (matchedArtistsCount > 0) {
59
+ score += 20;
60
+ }
61
+ }
62
+
63
+ if (targetDurationMs !== null && track.duration_ms) {
64
+ const diffSec = Math.abs(track.duration_ms - targetDurationMs) / 1000;
65
+ if (diffSec <= 2) {
66
+ score += 30;
67
+ } else if (diffSec <= 5) {
68
+ score += 20;
69
+ } else if (diffSec <= 10) {
70
+ score += 10;
71
+ } else if (diffSec > 30) {
72
+ score -= 20;
73
+ }
74
+ }
75
+
76
+ if (score > bestScore) {
77
+ bestScore = score;
78
+ bestMatch = track;
79
+ }
80
+ }
81
+
82
+ return bestScore >= 20 ? bestMatch : null;
83
+ };
84
+
85
+ export const fetchLyrics = async (req, res) => {
86
+ const { trackId, name, song, track, artist, duration } = req.query;
87
+
88
+ // 1. Direct track ID lookup
89
+ if (trackId) {
90
+ const lyricsData = await getLyrics(trackId);
91
+ if (!lyricsData) {
92
+ return res.status(500).json({ error: 'Failed to fetch lyrics data' });
93
+ }
94
+ return res.json(lyricsData);
95
+ }
96
+
97
+ // 2. Search and match mode
98
+ const targetSongName = name || song || track;
99
+ if (!targetSongName) {
100
+ return res.status(400).json({ error: 'Missing trackId or name parameter' });
101
+ }
102
+
103
+ try {
104
+ // Build search query
105
+ const searchQuery = artist ? `${targetSongName} ${artist}` : targetSongName;
106
+
107
+ console.log(`Searching Spotify GraphQL for lyrics: "${searchQuery}"`);
108
+ const candidates = await searchSpotifyGraphQL(searchQuery, 20);
109
+
110
+ if (candidates.length === 0) {
111
+ return res.status(404).json({ error: 'No matching tracks found on Spotify' });
112
+ }
113
+
114
+ const matchedTrack = findBestMatch(candidates, targetSongName, artist, duration);
115
+ if (!matchedTrack) {
116
+ return res.status(404).json({ error: 'No track matching the name, artist, and duration criteria was found' });
117
+ }
118
+
119
+ console.log(`Matched track for lyrics: "${matchedTrack.name}" (${matchedTrack.id})`);
120
+
121
+ const lyricsData = await getLyrics(matchedTrack.id);
122
+ if (!lyricsData) {
123
+ return res.status(500).json({ error: 'Failed to fetch lyrics data for the matched track' });
124
+ }
125
+
126
+ res.json({
127
+ matchedTrack: {
128
+ id: matchedTrack.id,
129
+ name: matchedTrack.name,
130
+ artist: matchedTrack.artists?.map(a => a.name).join(', '),
131
+ durationMs: matchedTrack.duration_ms
132
+ },
133
+ ...lyricsData
134
+ });
135
+ } catch (error) {
136
+ console.error('Fetch lyrics error:', error.response?.data || error.message);
137
+ res.status(500).json({ error: 'An error occurred while fetching lyrics data' });
138
+ }
139
+ };
index.js CHANGED
@@ -1,11 +1,13 @@
1
  import express from 'express';
2
  import canvasRoutes from './routes/canvasRoutes.js';
 
3
  import { initPersistentBrowser } from './services/browserAuthService.js';
4
 
5
  const app = express();
6
  const PORT = process.env.PORT || 7860;
7
 
8
  app.use('/api/canvas', canvasRoutes);
 
9
 
10
  app.listen(PORT, async function () {
11
  console.log("Listening on PORT: ", PORT);
 
1
  import express from 'express';
2
  import canvasRoutes from './routes/canvasRoutes.js';
3
+ import lyricsRoutes from './routes/lyricsRoutes.js';
4
  import { initPersistentBrowser } from './services/browserAuthService.js';
5
 
6
  const app = express();
7
  const PORT = process.env.PORT || 7860;
8
 
9
  app.use('/api/canvas', canvasRoutes);
10
+ app.use('/api/lyrics', lyricsRoutes);
11
 
12
  app.listen(PORT, async function () {
13
  console.log("Listening on PORT: ", PORT);
routes/lyricsRoutes.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import express from 'express';
2
+ import { fetchLyrics } from '../controllers/lyricsController.js';
3
+
4
+ const router = express.Router();
5
+
6
+ router.get('/', fetchLyrics);
7
+
8
+ export default router;
services/spotifyLyricsService.js ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import axios from 'axios';
2
+ import { getBrowserCredentials } from './browserAuthService.js';
3
+
4
+ export async function getLyrics(trackId, imageUri = '') {
5
+ try {
6
+ const { authorization, clientToken } = await getBrowserCredentials();
7
+
8
+ // Construct the endpoint path depending on whether imageUri is provided
9
+ let url = `https://spclient.wg.spotify.com/color-lyrics/v2/track/${trackId}`;
10
+ if (imageUri) {
11
+ url += `/image/${encodeURIComponent(imageUri)}`;
12
+ }
13
+ url += '?format=json&vocalRemoval=false&market=from_token';
14
+
15
+ const response = await axios.get(url, {
16
+ headers: {
17
+ 'Accept': 'application/json',
18
+ 'Accept-Language': 'en-GB',
19
+ 'App-Platform': 'WebPlayer',
20
+ 'Authorization': `Bearer ${authorization}`,
21
+ 'Client-Token': clientToken,
22
+ 'Origin': 'https://open.spotify.com',
23
+ 'Referer': 'https://open.spotify.com/',
24
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36',
25
+ 'Spotify-App-Version': '1.2.95.154.g2abc6fb9'
26
+ }
27
+ });
28
+
29
+ return response.data;
30
+ } catch (error) {
31
+ console.error(`Lyrics request error for track ${trackId}:`, error.response?.data || error.message);
32
+ return null;
33
+ }
34
+ }