veltrixcode commited on
Commit
2d2e00c
·
verified ·
1 Parent(s): 737d8f0

Upload 15 files

Browse files
Dockerfile CHANGED
@@ -1,39 +1,22 @@
1
- FROM ubuntu:22.04
2
-
3
- ENV DEBIAN_FRONTEND=noninteractive \
4
- PYTHONUNBUFFERED=1 \
5
- PIP_NO_CACHE_DIR=1 \
6
- PORT=7860
7
-
8
- # System deps and Python 3.10 (default in Ubuntu 22.04)
9
- RUN apt-get update && apt-get install -y --no-install-recommends \
10
- ca-certificates \
11
- curl \
12
- git \
13
- build-essential \
14
- pkg-config \
15
- python3 \
16
- python3-pip \
17
- python3-venv \
18
- python3-distutils \
19
- && update-ca-certificates \
20
- && rm -rf /var/lib/apt/lists/*
21
 
22
  WORKDIR /app
23
 
24
- # Copy only requirements first for better layer caching
25
- COPY requirements.txt /app/requirements.txt
26
- RUN python3 -m pip install --upgrade pip \
27
- && python3 -m pip install -r /app/requirements.txt
28
 
29
  # Copy source
30
- COPY . /app
31
 
32
- # Non-root user
33
- RUN useradd -m -u 1000 appuser
34
- USER appuser
35
 
36
  EXPOSE 7860
37
 
38
- # Hugging Face Spaces provides $PORT
39
- CMD ["sh", "-c", "waitress-serve --host=0.0.0.0 --port=${PORT:-7860} app:app"]
 
 
1
+ # Node.js Dockerfile for Hugging Face Spaces (Docker runtime)
2
+
3
+ FROM node:20-alpine AS base
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  WORKDIR /app
6
 
7
+ # Install dependencies
8
+ COPY package.json package-lock.json* ./
9
+ RUN npm ci --only=production || npm install --production
 
10
 
11
  # Copy source
12
+ COPY . .
13
 
14
+ ENV NODE_ENV=production
15
+ # HF Spaces exposes a dynamic $PORT; default to 7860 for local runs
16
+ ENV PORT=7860
17
 
18
  EXPOSE 7860
19
 
20
+ CMD ["node", "app.js"]
21
+
22
+
app.js ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const cors = require('cors');
3
+ const helmet = require('helmet');
4
+ const morgan = require('morgan');
5
+ const swaggerJsdoc = require('swagger-jsdoc');
6
+ const swaggerUi = require('swagger-ui-express');
7
+ require('dotenv').config();
8
+
9
+ // Import route modules
10
+ const apiRoutes = require('./routes/api');
11
+ const entitiesRoutes = require('./routes/entities');
12
+ const exploreRoutes = require('./routes/explore');
13
+ const youtubeRoutes = require('./routes/youtube');
14
+ const jiosaavnRoutes = require('./routes/jiosaavn');
15
+
16
+ // Import libraries
17
+ const YTMusic = require('./lib/ytmusicapi');
18
+ const YouTubeSearch = require('./lib/youtube-search');
19
+
20
+ const app = express();
21
+ const PORT = process.env.PORT || 5000;
22
+
23
+ // Middleware
24
+ app.use(helmet());
25
+ app.use(morgan('combined'));
26
+ app.use(cors({
27
+ origin: '*',
28
+ methods: ['GET', 'POST', 'PUT', 'DELETE'],
29
+ allowedHeaders: ['Content-Type', 'Authorization']
30
+ }));
31
+ app.use(express.json());
32
+ app.use(express.urlencoded({ extended: true }));
33
+
34
+ // Initialize clients
35
+ const ytmusic = new YTMusic();
36
+ const youtubeSearch = new YouTubeSearch();
37
+
38
+ // Make clients available to routes
39
+ app.locals.ytmusic = ytmusic;
40
+ app.locals.youtubeSearch = youtubeSearch;
41
+
42
+ // Health check endpoint
43
+ app.get('/health', (req, res) => {
44
+ res.json({ status: 'ok' });
45
+ });
46
+
47
+ // Swagger configuration
48
+ const swaggerOptions = {
49
+ definition: {
50
+ openapi: '3.0.0',
51
+ info: {
52
+ title: 'Music API',
53
+ version: '1.0.0',
54
+ description: 'Node.js Music API with YouTube Music, YouTube Search, and JioSaavn integration',
55
+ },
56
+ servers: [
57
+ {
58
+ url: `http://localhost:${PORT}`,
59
+ description: 'Development server',
60
+ },
61
+ ],
62
+ },
63
+ apis: ['./routes/*.js'], // Path to the API docs
64
+ };
65
+
66
+ const specs = swaggerJsdoc(swaggerOptions);
67
+ app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
68
+
69
+ // API routes
70
+ app.use('/api', apiRoutes);
71
+ app.use('/api', entitiesRoutes);
72
+ app.use('/api', exploreRoutes);
73
+ app.use('/api', youtubeRoutes);
74
+ app.use('/api', jiosaavnRoutes);
75
+
76
+ // Error handling middleware
77
+ app.use((err, req, res, next) => {
78
+ console.error(err.stack);
79
+ res.status(500).json({
80
+ error: 'Something went wrong!',
81
+ message: process.env.NODE_ENV === 'development' ? err.message : 'Internal server error'
82
+ });
83
+ });
84
+
85
+ // 404 handler
86
+ app.use('*', (req, res) => {
87
+ res.status(404).json({
88
+ error: 'Route not found',
89
+ message: `Cannot ${req.method} ${req.originalUrl}`
90
+ });
91
+ });
92
+
93
+ // Start server locally; on Vercel we just export the app
94
+ if (!process.env.VERCEL) {
95
+ app.listen(PORT, '0.0.0.0', () => {
96
+ console.log(`🚀 Music API server running on port ${PORT}`);
97
+ console.log(`📚 API Documentation available at http://localhost:${PORT}/api-docs`);
98
+ console.log(`🏥 Health check available at http://localhost:${PORT}/health`);
99
+ });
100
+ }
101
+
102
+ module.exports = app;
lib/.DS_Store ADDED
Binary file (6.15 kB). View file
 
lib/jiosaavn.js ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const axios = require('axios');
2
+
3
+ class JioSaavn {
4
+ constructor() {
5
+ this.baseURL = 'https://fragrant-rain-244a.bob17040246.workers.dev/api.php';
6
+ this.headers = {
7
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
8
+ 'Accept': 'application/json, text/plain, */*',
9
+ 'Accept-Language': 'en-US,en;q=0.9',
10
+ 'Accept-Encoding': 'gzip, deflate, br',
11
+ 'Connection': 'keep-alive'
12
+ };
13
+ }
14
+
15
+ /**
16
+ * Search for music on JioSaavn
17
+ * @param {string} title - Song title
18
+ * @param {string} artist - Artist name
19
+ * @param {boolean} debug - Enable debug mode
20
+ * @returns {Promise<Object>} Song information with download URL
21
+ */
22
+ async search(title, artist, debug = false) {
23
+ try {
24
+ const searchQuery = `${title} ${artist}`;
25
+ const url = this._buildSearchURL(searchQuery);
26
+
27
+ console.log(`[JioSaavn] /jiosaavn/search title='${title}' artist='${artist}' url='${url}'`);
28
+
29
+ const startTime = Date.now();
30
+ const response = await axios.get(url, {
31
+ headers: this.headers,
32
+ timeout: 15000
33
+ });
34
+ const duration = Date.now() - startTime;
35
+
36
+ console.log(`[JioSaavn] status=${response.status} time_ms=${duration} len=${response.data.length} content_type='${response.headers['content-type']}'`);
37
+
38
+ if (!response.data || typeof response.data !== 'object') {
39
+ throw new Error('Invalid response format from JioSaavn API');
40
+ }
41
+
42
+ const results = response.data.results || [];
43
+ console.log(`[JioSaavn] results_count=${results.length}`);
44
+
45
+ if (results.length === 0) {
46
+ throw new Error('Music stream not found in JioSaavn results');
47
+ }
48
+
49
+ // Process results
50
+ const processedResults = results.map(rawSong => this._createSongPayload(rawSong));
51
+ console.log(`[JioSaavn] processed_count=${processedResults.length} sample_titles=${processedResults.slice(0, 3).map(r => r.name)}`);
52
+
53
+ // Find matching track
54
+ const matchingTrack = this._findMatchingTrack(processedResults, title, artist, debug);
55
+
56
+ if (!matchingTrack) {
57
+ throw new Error('Music stream not found in JioSaavn results');
58
+ }
59
+
60
+ // Create final response
61
+ const finalResponse = {
62
+ name: matchingTrack.name,
63
+ year: matchingTrack.year,
64
+ copyright: matchingTrack.copyright,
65
+ duration: matchingTrack.duration,
66
+ label: matchingTrack.label,
67
+ albumName: matchingTrack.album?.name || null,
68
+ artists: [
69
+ ...(matchingTrack.artists?.primary || []),
70
+ ...(matchingTrack.artists?.featured || []),
71
+ ...(matchingTrack.artists?.all || [])
72
+ ],
73
+ downloadUrl: matchingTrack.downloadUrl
74
+ };
75
+
76
+ if (debug) {
77
+ finalResponse._debug = {
78
+ queried_url: url,
79
+ time_ms: duration,
80
+ matched_artists: matchingTrack.artists
81
+ };
82
+ }
83
+
84
+ return finalResponse;
85
+ } catch (error) {
86
+ console.error(`[JioSaavn][ERR] ${error.message}`);
87
+ throw new Error(`JioSaavn search failed: ${error.message}`);
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Search for all music results on JioSaavn
93
+ * @param {string} query - Search query
94
+ * @param {number} limit - Number of results to return
95
+ * @param {boolean} debug - Enable debug mode
96
+ * @returns {Promise<Object>} All matching songs
97
+ */
98
+ async searchAll(query, limit = 10, debug = false) {
99
+ try {
100
+ const url = this._buildSearchURL(query, limit);
101
+
102
+ console.log(`[JioSaavn] /jiosaavn/search/all q='${query}' limit=${limit} url='${url}'`);
103
+
104
+ const startTime = Date.now();
105
+ const response = await axios.get(url, {
106
+ headers: this.headers,
107
+ timeout: 15000
108
+ });
109
+ const duration = Date.now() - startTime;
110
+
111
+ console.log(`[JioSaavn] status=${response.status} time_ms=${duration} len=${response.data.length} content_type='${response.headers['content-type']}'`);
112
+
113
+ if (!response.data || typeof response.data !== 'object') {
114
+ throw new Error('Invalid response format from JioSaavn API');
115
+ }
116
+
117
+ const results = response.data.results || [];
118
+ console.log(`[JioSaavn] results_count=${results.length}`);
119
+
120
+ if (results.length === 0) {
121
+ return { results: [] };
122
+ }
123
+
124
+ // Process all results
125
+ const processedResults = results.map(rawSong => this._createSongPayload(rawSong));
126
+ console.log(`[JioSaavn] processed_count=${processedResults.length} sample_titles=${processedResults.slice(0, 3).map(r => r.name)}`);
127
+
128
+ const response_data = {
129
+ query,
130
+ total: processedResults.length,
131
+ results: processedResults
132
+ };
133
+
134
+ if (debug) {
135
+ response_data._debug = {
136
+ queried_url: url,
137
+ time_ms: duration
138
+ };
139
+ }
140
+
141
+ return response_data;
142
+ } catch (error) {
143
+ console.error(`[JioSaavn][ERR] ${error.message}`);
144
+ throw new Error(`JioSaavn search all failed: ${error.message}`);
145
+ }
146
+ }
147
+
148
+ // Private helper methods
149
+ _buildSearchURL(query, limit = 10) {
150
+ const params = new URLSearchParams({
151
+ _format: 'json',
152
+ _marker: '0',
153
+ api_version: '4',
154
+ ctx: 'web6dot0',
155
+ __call: 'search.getResults',
156
+ q: query,
157
+ p: '0',
158
+ n: limit.toString()
159
+ });
160
+
161
+ return `${this.baseURL}?${params.toString()}`;
162
+ }
163
+
164
+ _createSongPayload(rawSong) {
165
+ return {
166
+ name: rawSong.title || rawSong.song || '',
167
+ year: rawSong.year || '',
168
+ copyright: rawSong.copyright || '',
169
+ duration: rawSong.duration || '',
170
+ label: rawSong.label || '',
171
+ album: {
172
+ name: rawSong.album || rawSong.album_name || '',
173
+ id: rawSong.album_id || ''
174
+ },
175
+ artists: {
176
+ primary: this._parseArtists(rawSong.primary_artists || rawSong.artists || []),
177
+ featured: this._parseArtists(rawSong.featured_artists || []),
178
+ all: this._parseArtists(rawSong.all_artists || [])
179
+ },
180
+ downloadUrl: rawSong.download_url || rawSong.media_url || rawSong.media_preview_url || '',
181
+ image: rawSong.image || rawSong.thumbnail || '',
182
+ language: rawSong.language || '',
183
+ genre: rawSong.genre || ''
184
+ };
185
+ }
186
+
187
+ _parseArtists(artists) {
188
+ if (!Array.isArray(artists)) {
189
+ return [];
190
+ }
191
+
192
+ return artists.map(artist => {
193
+ if (typeof artist === 'string') {
194
+ return { name: artist, id: '' };
195
+ }
196
+ return {
197
+ name: artist.name || artist.title || '',
198
+ id: artist.id || ''
199
+ };
200
+ });
201
+ }
202
+
203
+ _findMatchingTrack(processedResults, title, artist, debug) {
204
+ const normalizeString = (text) => {
205
+ return (text || '').toString().trim().toLowerCase().replace(/[^\w\s]/g, '');
206
+ };
207
+
208
+ const startsEither = (a, b) => {
209
+ return a.startsWith(b) || b.startsWith(a);
210
+ };
211
+
212
+ for (const track of processedResults) {
213
+ // Get all artist names
214
+ const primaryArtists = (track.artists?.primary || []).map(a => a.name?.trim()).filter(Boolean);
215
+ const singers = (track.artists?.all || []).filter(a => a.role === 'singer').map(a => a.name?.trim()).filter(Boolean);
216
+ const allArtists = [...primaryArtists, ...singers];
217
+
218
+ // Check if artist matches
219
+ const artistInput = normalizeString(artist);
220
+ let artistMatches = false;
221
+
222
+ if (allArtists.length > 0) {
223
+ for (const trackArtistName of allArtists) {
224
+ if (startsEither(artistInput, normalizeString(trackArtistName))) {
225
+ artistMatches = true;
226
+ break;
227
+ }
228
+ }
229
+ }
230
+
231
+ // Check if title matches
232
+ const titleMatches = startsEither(normalizeString(title), normalizeString(track.name));
233
+
234
+ if (debug) {
235
+ console.log(`[JioSaavn][match_check] track='${track.name}' artists=${allArtists} title_matches=${titleMatches} artist_matches=${artistMatches}`);
236
+ }
237
+
238
+ if (titleMatches && (artistMatches || allArtists.length === 0)) {
239
+ return track;
240
+ }
241
+ }
242
+
243
+ // Fallback: choose the first with title match only
244
+ const titleOnly = processedResults.find(t =>
245
+ startsEither(normalizeString(title), normalizeString(t.name))
246
+ );
247
+
248
+ if (titleOnly) {
249
+ console.log('[JioSaavn] Falling back to title-only match');
250
+ return titleOnly;
251
+ }
252
+
253
+ // Log a concise summary to help debugging
254
+ const sample = processedResults.slice(0, 5).map(tr => ({
255
+ name: tr.name,
256
+ artists: (tr.artists?.primary || []).map(a => a.name)
257
+ }));
258
+ console.log(`[JioSaavn] No exact match after processing. sample_candidates=${JSON.stringify(sample)}`);
259
+
260
+ return null;
261
+ }
262
+ }
263
+
264
+ module.exports = JioSaavn;
lib/youtube-search.js ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const axios = require('axios');
2
+
3
+ class YouTubeSearch {
4
+ constructor() {
5
+ this.baseURL = 'https://www.youtube.com';
6
+ this.searchURL = 'https://www.youtube.com/results';
7
+ this.continuationURL = 'https://www.youtube.com/youtubei/v1/search';
8
+ this.suggestionsURL = 'https://suggestqueries-clients6.youtube.com/complete/search';
9
+ this.headers = {
10
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
11
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
12
+ 'Accept-Language': 'en-US,en;q=0.5',
13
+ 'Accept-Encoding': 'gzip, deflate',
14
+ 'DNT': '1',
15
+ 'Connection': 'keep-alive',
16
+ 'Upgrade-Insecure-Requests': '1'
17
+ };
18
+ this.apiKey = null; // Will be extracted from initial page
19
+ this.clientVersion = null;
20
+ }
21
+
22
+ /**
23
+ * Extract API key and client version from initial page load
24
+ */
25
+ async _extractAPIConfig(html) {
26
+ try {
27
+ const apiKeyMatch = html.match(/"INNERTUBE_API_KEY":"([^"]+)"/);
28
+ const clientVersionMatch = html.match(/"clientVersion":"([^"]+)"/);
29
+
30
+ if (apiKeyMatch) this.apiKey = apiKeyMatch[1];
31
+ if (clientVersionMatch) this.clientVersion = clientVersionMatch[1];
32
+ } catch (error) {
33
+ console.error('Error extracting API config:', error);
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Make a continuation request using POST
39
+ */
40
+ async _fetchContinuation(continuationToken) {
41
+ try {
42
+ if (!this.apiKey) {
43
+ throw new Error('API key not initialized. Make an initial search first.');
44
+ }
45
+
46
+ const response = await axios.post(
47
+ `${this.continuationURL}?key=${this.apiKey}`,
48
+ {
49
+ continuation: continuationToken,
50
+ context: {
51
+ client: {
52
+ clientName: 'WEB',
53
+ clientVersion: this.clientVersion || '2.20231219.01.00'
54
+ }
55
+ }
56
+ },
57
+ {
58
+ headers: {
59
+ 'Content-Type': 'application/json',
60
+ 'User-Agent': this.headers['User-Agent'],
61
+ 'Accept': '*/*',
62
+ 'Accept-Language': 'en-US,en;q=0.5'
63
+ }
64
+ }
65
+ );
66
+
67
+ return response.data;
68
+ } catch (error) {
69
+ throw new Error(`Continuation request failed: ${error.message}`);
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Search for videos on YouTube
75
+ * @param {string} query - Search query
76
+ * @param {string} continuationToken - Continuation token for pagination
77
+ * @returns {Promise<Object>} Search results with continuation token
78
+ */
79
+ async searchVideos(query, continuationToken = null) {
80
+ try {
81
+ if (continuationToken) {
82
+ // Use POST request for continuation
83
+ const data = await this._fetchContinuation(continuationToken);
84
+ return this._parseContinuationResults(data, 'video');
85
+ }
86
+
87
+ // FIXED: Require query for initial search
88
+ if (!query) {
89
+ throw new Error('Query is required for initial search');
90
+ }
91
+
92
+ // Initial search with GET request
93
+ const response = await axios.get(this.searchURL, {
94
+ params: {
95
+ search_query: query,
96
+ sp: 'EgIQAQ%253D%253D'
97
+ },
98
+ headers: this.headers
99
+ });
100
+
101
+ // Extract API config for continuation requests
102
+ await this._extractAPIConfig(response.data);
103
+ return this._parseVideoResults(response.data);
104
+ } catch (error) {
105
+ throw new Error(`Video search failed: ${error.message}`);
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Search for channels on YouTube
111
+ * @param {string} query - Search query
112
+ * @param {string} continuationToken - Continuation token for pagination
113
+ * @returns {Promise<Object>} Search results with continuation token
114
+ */
115
+ async searchChannels(query, continuationToken = null) {
116
+ try {
117
+ if (continuationToken) {
118
+ const data = await this._fetchContinuation(continuationToken);
119
+ return this._parseContinuationResults(data, 'channel');
120
+ }
121
+
122
+ // FIXED: Require query for initial search
123
+ if (!query) {
124
+ throw new Error('Query is required for initial search');
125
+ }
126
+
127
+ const response = await axios.get(this.searchURL, {
128
+ params: {
129
+ search_query: query,
130
+ sp: 'EgIQAg%253D%253D'
131
+ },
132
+ headers: this.headers
133
+ });
134
+
135
+ await this._extractAPIConfig(response.data);
136
+ return this._parseChannelResults(response.data);
137
+ } catch (error) {
138
+ throw new Error(`Channel search failed: ${error.message}`);
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Search for playlists on YouTube
144
+ * @param {string} query - Search query
145
+ * @param {string} continuationToken - Continuation token for pagination
146
+ * @returns {Promise<Object>} Search results with continuation token
147
+ */
148
+ async searchPlaylists(query, continuationToken = null) {
149
+ try {
150
+ if (continuationToken) {
151
+ const data = await this._fetchContinuation(continuationToken);
152
+ return this._parseContinuationResults(data, 'playlist');
153
+ }
154
+
155
+ // FIXED: Require query for initial search
156
+ if (!query) {
157
+ throw new Error('Query is required for initial search');
158
+ }
159
+
160
+ const response = await axios.get(this.searchURL, {
161
+ params: {
162
+ search_query: query,
163
+ sp: 'EgIQAw%253D%253D'
164
+ },
165
+ headers: this.headers
166
+ });
167
+
168
+ await this._extractAPIConfig(response.data);
169
+ return this._parsePlaylistResults(response.data);
170
+ } catch (error) {
171
+ throw new Error(`Playlist search failed: ${error.message}`);
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Parse continuation response data
177
+ */
178
+ _parseContinuationResults(data, type) {
179
+ const results = [];
180
+ let nextContinuationToken = null;
181
+
182
+ try {
183
+ const actions = data?.onResponseReceivedCommands || data?.onResponseReceivedActions || [];
184
+
185
+ for (const action of actions) {
186
+ const items = action?.appendContinuationItemsAction?.continuationItems || [];
187
+
188
+ const pushByType = (node) => {
189
+ if (!node) return;
190
+ if (type === 'video' && node.videoRenderer) {
191
+ const v = this._parseVideoRenderer(node.videoRenderer);
192
+ if (v) results.push(v);
193
+ } else if (type === 'channel' && node.channelRenderer) {
194
+ const c = this._parseChannelRenderer(node.channelRenderer);
195
+ if (c) results.push(c);
196
+ } else if (type === 'playlist' && node.playlistRenderer) {
197
+ const p = this._parsePlaylistRenderer(node.playlistRenderer);
198
+ if (p) results.push(p);
199
+ } else if (node.richItemRenderer?.content) {
200
+ // richItemRenderer wrapper
201
+ pushByType(node.richItemRenderer.content);
202
+ } else if (node.itemSectionRenderer?.contents) {
203
+ // sometimes continuationItems embed an itemSectionRenderer again
204
+ for (const inner of node.itemSectionRenderer.contents) {
205
+ pushByType(inner);
206
+ }
207
+ }
208
+ };
209
+
210
+ for (const item of items) {
211
+ if (item.continuationItemRenderer) {
212
+ nextContinuationToken = item.continuationItemRenderer?.continuationEndpoint?.continuationCommand?.token;
213
+ continue;
214
+ }
215
+ pushByType(item);
216
+ }
217
+ }
218
+ } catch (error) {
219
+ console.error('Error parsing continuation results:', error);
220
+ }
221
+
222
+ return { results, continuationToken: nextContinuationToken };
223
+ }
224
+
225
+ /**
226
+ * Get search suggestions from YouTube
227
+ * @param {string} query - Partial query
228
+ * @returns {Promise<Array>} Search suggestions
229
+ */
230
+ async getSuggestions(query) {
231
+ try {
232
+ const response = await axios.get(this.suggestionsURL, {
233
+ params: {
234
+ ds: 'yt',
235
+ hl: 'en',
236
+ gl: 'US',
237
+ client: 'youtube',
238
+ q: query
239
+ },
240
+ headers: this.headers
241
+ });
242
+
243
+ return this._parseSuggestions(response.data);
244
+ } catch (error) {
245
+ return this._getStaticSuggestions(query);
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Get channel information by channel ID
251
+ * @param {string} channelId - YouTube channel ID
252
+ * @returns {Promise<Object>} Channel information
253
+ */
254
+ async getChannelInfo(channelId) {
255
+ try {
256
+ const response = await axios.get(`${this.baseURL}/channel/${channelId}`, {
257
+ headers: this.headers
258
+ });
259
+
260
+ return this._parseChannelInfo(response.data);
261
+ } catch (error) {
262
+ throw new Error(`Channel info failed: ${error.message}`);
263
+ }
264
+ }
265
+
266
+ // Private helper methods
267
+ _parseVideoResults(html) {
268
+ const results = [];
269
+ let nextContinuationToken = null;
270
+
271
+ try {
272
+ const jsonMatch = html.match(/var ytInitialData = ({.+?});/);
273
+ if (!jsonMatch) {
274
+ return { results, continuationToken: nextContinuationToken };
275
+ }
276
+
277
+ const data = JSON.parse(jsonMatch[1]);
278
+ const primary = data?.contents?.twoColumnSearchResultsRenderer?.primaryContents;
279
+ const sections = primary?.sectionListRenderer?.contents || [];
280
+ const items = sections[0]?.itemSectionRenderer?.contents || [];
281
+
282
+ for (const item of items) {
283
+ if (item.videoRenderer) {
284
+ const v = this._parseVideoRenderer(item.videoRenderer);
285
+ if (v) results.push(v);
286
+ } else if (item.richItemRenderer?.content?.videoRenderer) {
287
+ const v = this._parseVideoRenderer(item.richItemRenderer.content.videoRenderer);
288
+ if (v) results.push(v);
289
+ }
290
+ }
291
+
292
+ nextContinuationToken = this._extractContinuationToken(data);
293
+ } catch (error) {
294
+ console.error('Error parsing video results:', error);
295
+ }
296
+
297
+ return { results, continuationToken: nextContinuationToken };
298
+ }
299
+
300
+ _parseChannelResults(html) {
301
+ const results = [];
302
+ let nextContinuationToken = null;
303
+
304
+ try {
305
+ const jsonMatch = html.match(/var ytInitialData = ({.+?});/);
306
+ if (!jsonMatch) {
307
+ return { results, continuationToken: nextContinuationToken };
308
+ }
309
+
310
+ const data = JSON.parse(jsonMatch[1]);
311
+ const contents = data?.contents?.twoColumnSearchResultsRenderer?.primaryContents?.sectionListRenderer?.contents || [];
312
+
313
+ for (const section of contents) {
314
+ const items = section?.itemSectionRenderer?.contents || [];
315
+ for (const item of items) {
316
+ if (item.channelRenderer) {
317
+ const channel = this._parseChannelRenderer(item.channelRenderer);
318
+ if (channel) results.push(channel);
319
+ }
320
+ }
321
+ }
322
+
323
+ nextContinuationToken = this._extractContinuationToken(data);
324
+ } catch (error) {
325
+ console.error('Error parsing channel results:', error);
326
+ }
327
+
328
+ return { results, continuationToken: nextContinuationToken };
329
+ }
330
+
331
+ _parsePlaylistResults(html) {
332
+ const results = [];
333
+ let nextContinuationToken = null;
334
+
335
+ try {
336
+ const jsonMatch = html.match(/var ytInitialData = ({.+?});/);
337
+ if (!jsonMatch) {
338
+ return { results, continuationToken: nextContinuationToken };
339
+ }
340
+
341
+ const data = JSON.parse(jsonMatch[1]);
342
+ const contents = data?.contents?.twoColumnSearchResultsRenderer?.primaryContents?.sectionListRenderer?.contents || [];
343
+
344
+ for (const section of contents) {
345
+ const items = section?.itemSectionRenderer?.contents || [];
346
+ for (const item of items) {
347
+ if (item.playlistRenderer) {
348
+ const playlist = this._parsePlaylistRenderer(item.playlistRenderer);
349
+ if (playlist) results.push(playlist);
350
+ }
351
+ }
352
+ }
353
+
354
+ nextContinuationToken = this._extractContinuationToken(data);
355
+ } catch (error) {
356
+ console.error('Error parsing playlist results:', error);
357
+ }
358
+
359
+ return { results, continuationToken: nextContinuationToken };
360
+ }
361
+
362
+ _extractContinuationToken(data) {
363
+ try {
364
+ const sections = data?.contents?.twoColumnSearchResultsRenderer?.primaryContents?.sectionListRenderer?.contents || [];
365
+
366
+ for (const section of sections) {
367
+ if (section.continuationItemRenderer) {
368
+ return section.continuationItemRenderer?.continuationEndpoint?.continuationCommand?.token || null;
369
+ }
370
+
371
+ const items = section?.itemSectionRenderer?.contents || [];
372
+ for (const it of items) {
373
+ if (it.continuationItemRenderer) {
374
+ return it.continuationItemRenderer?.continuationEndpoint?.continuationCommand?.token || null;
375
+ }
376
+ }
377
+ }
378
+ } catch (error) {
379
+ console.error('Error extracting continuation token:', error);
380
+ }
381
+
382
+ return null;
383
+ }
384
+
385
+ _parseVideoRenderer(videoRenderer) {
386
+ const videoId = videoRenderer.videoId;
387
+ const titleRun = videoRenderer.title?.runs?.[0];
388
+ const title = titleRun?.text;
389
+ const accessibilityTitle = videoRenderer.title?.accessibility?.accessibilityData?.label || title || null;
390
+ const accessibilityDuration = videoRenderer.lengthText?.accessibility?.accessibilityData?.label || null;
391
+ const duration = videoRenderer.lengthText?.simpleText || null;
392
+ const ownerRun = videoRenderer.ownerText?.runs?.[0];
393
+ const channelId = ownerRun?.navigationEndpoint?.browseEndpoint?.browseId || null;
394
+ const channelName = ownerRun?.text || null;
395
+ const channelLink = channelId ? `https://www.youtube.com/channel/${channelId}` : null;
396
+ const channelThumbs = videoRenderer.channelThumbnailSupportedRenderers?.channelThumbnailWithLinkRenderer?.thumbnail?.thumbnails || [];
397
+ const channelThumbnails = channelThumbs.map(t => ({ url: t.url, width: t.width, height: t.height }));
398
+ const descRuns = videoRenderer.descriptionSnippet?.runs || [];
399
+ const descriptionSnippet = descRuns.map(r => ({ text: r.text, bold: !!r.bold }));
400
+ const thumbs = videoRenderer.thumbnail?.thumbnails || [];
401
+ const thumbnails = thumbs.map(t => ({ url: t.url, width: t.width, height: t.height }));
402
+ const richThumbList = videoRenderer.richThumbnail?.movingThumbnailRenderer?.movingThumbnailDetails?.thumbnails
403
+ || videoRenderer.richThumbnail?.movingThumbnailRenderer?.thumbnail?.thumbnails
404
+ || [];
405
+ const richThumb = richThumbList.length ? richThumbList[0] : null;
406
+ const richThumbnail = richThumb ? { url: richThumb.url, width: richThumb.width, height: richThumb.height } : null;
407
+ const publishedTime = videoRenderer.publishedTimeText?.simpleText || null;
408
+ const fullViewText = videoRenderer.viewCountText?.simpleText || null;
409
+ const shortViewText = videoRenderer.shortViewCountText?.simpleText || null;
410
+ const viewCount = (fullViewText || shortViewText)
411
+ ? { text: fullViewText || shortViewText, short: shortViewText || fullViewText }
412
+ : null;
413
+
414
+ return {
415
+ accessibility: {
416
+ duration: accessibilityDuration,
417
+ title: accessibilityTitle
418
+ },
419
+ channel: {
420
+ id: channelId,
421
+ link: channelLink,
422
+ name: channelName,
423
+ thumbnails: channelThumbnails
424
+ },
425
+ descriptionSnippet,
426
+ duration,
427
+ id: videoId,
428
+ link: `https://www.youtube.com/watch?v=${videoId}`,
429
+ publishedTime,
430
+ richThumbnail,
431
+ shelfTitle: null,
432
+ thumbnails,
433
+ title,
434
+ type: 'video',
435
+ viewCount
436
+ };
437
+ }
438
+
439
+ _parseChannelRenderer(channelRenderer) {
440
+ const title = channelRenderer.title?.simpleText;
441
+ const channelId = channelRenderer.channelId;
442
+ const thumbnail = channelRenderer.thumbnail?.thumbnails?.[0]?.url;
443
+ const subscriberCount = channelRenderer.subscriberCountText?.simpleText;
444
+ const videoCount = channelRenderer.videoCountText?.simpleText;
445
+ const description = channelRenderer.descriptionSnippet?.runs?.[0]?.text;
446
+
447
+ return {
448
+ type: 'channel',
449
+ channelId,
450
+ title,
451
+ thumbnail,
452
+ subscriberCount,
453
+ videoCount,
454
+ description,
455
+ url: `https://www.youtube.com/channel/${channelId}`
456
+ };
457
+ }
458
+
459
+ _parsePlaylistRenderer(playlistRenderer) {
460
+ const title = playlistRenderer.title?.simpleText;
461
+ const playlistId = playlistRenderer.playlistId;
462
+ const thumbnail = playlistRenderer.thumbnails?.[0]?.thumbnails?.[0]?.url;
463
+ const videoCount = playlistRenderer.videoCount;
464
+ const author = playlistRenderer.shortBylineText?.runs?.[0]?.text;
465
+ const authorChannelId = playlistRenderer.shortBylineText?.runs?.[0]?.navigationEndpoint?.browseEndpoint?.browseId;
466
+
467
+ return {
468
+ type: 'playlist',
469
+ playlistId,
470
+ title,
471
+ thumbnail,
472
+ videoCount,
473
+ author,
474
+ authorChannelId,
475
+ url: `https://www.youtube.com/playlist?list=${playlistId}`
476
+ };
477
+ }
478
+
479
+ _parseSuggestions(data) {
480
+ try {
481
+ let jsonData = data;
482
+
483
+ if (data.startsWith('window.google.ac.h(') && data.endsWith(');')) {
484
+ jsonData = data.slice(20, -2);
485
+ } else if (data.startsWith('window.google.ac.s(') && data.endsWith(');')) {
486
+ jsonData = data.slice(20, -2);
487
+ }
488
+
489
+ const parsed = JSON.parse(jsonData);
490
+ const suggestions = [];
491
+
492
+ if (parsed[1] && Array.isArray(parsed[1])) {
493
+ parsed[1].forEach(item => {
494
+ if (Array.isArray(item) && item[0]) {
495
+ suggestions.push(item[0]);
496
+ } else if (typeof item === 'string') {
497
+ suggestions.push(item);
498
+ }
499
+ });
500
+ }
501
+
502
+ return suggestions.slice(0, 10);
503
+ } catch (error) {
504
+ console.error('Error parsing suggestions:', error);
505
+ return this._getStaticSuggestions('');
506
+ }
507
+ }
508
+
509
+ _parseChannelInfo(html) {
510
+ try {
511
+ const jsonMatch = html.match(/var ytInitialData = ({.+?});/);
512
+ if (!jsonMatch) {
513
+ throw new Error('Could not parse channel data');
514
+ }
515
+
516
+ const data = JSON.parse(jsonMatch[1]);
517
+ const header = data?.header?.c4TabbedHeaderRenderer;
518
+
519
+ if (!header) {
520
+ throw new Error('Channel header not found');
521
+ }
522
+
523
+ return {
524
+ title: header.title,
525
+ channelId: header.channelId,
526
+ thumbnail: header.avatar?.thumbnails?.[0]?.url,
527
+ subscriberCount: header.subscriberCountText?.simpleText,
528
+ videoCount: header.videosCountText?.runs?.[0]?.text,
529
+ description: header.description?.simpleText
530
+ };
531
+ } catch (error) {
532
+ throw new Error(`Channel info parsing failed: ${error.message}`);
533
+ }
534
+ }
535
+
536
+ _getStaticSuggestions(query) {
537
+ const queryLower = query.toLowerCase();
538
+ const suggestionsMap = {
539
+ 'music': ['music', 'music video', 'music song', 'music 2024', 'music playlist'],
540
+ 'video': ['video', 'video song', 'video 2024', 'video download', 'video editing'],
541
+ 'movie': ['movie', 'movie trailer', 'movie song', 'movie review', 'movie 2024'],
542
+ 'song': ['song', 'song 2024', 'song download', 'song lyrics', 'song video'],
543
+ 'dance': ['dance', 'dance video', 'dance song', 'dance tutorial', 'dance 2024'],
544
+ 'comedy': ['comedy', 'comedy video', 'comedy show', 'comedy movie', 'comedy 2024'],
545
+ 'tutorial': ['tutorial', 'tutorial video', 'tutorial 2024', 'tutorial hindi', 'tutorial english'],
546
+ 'news': ['news', 'news today', 'news 2024', 'news hindi', 'news english'],
547
+ 'cooking': ['cooking', 'cooking video', 'cooking recipe', 'cooking tutorial', 'cooking 2024'],
548
+ 'fitness': ['fitness', 'fitness video', 'fitness workout', 'fitness tips', 'fitness 2024']
549
+ };
550
+
551
+ if (suggestionsMap[queryLower]) {
552
+ return suggestionsMap[queryLower];
553
+ }
554
+
555
+ for (const [key, suggestions] of Object.entries(suggestionsMap)) {
556
+ if (key.includes(queryLower) || queryLower.includes(key)) {
557
+ return suggestions;
558
+ }
559
+ }
560
+
561
+ return [query, `${query} video`, `${query} 2024`, `${query} tutorial`, `${query} song`];
562
+ }
563
+ }
564
+
565
+ module.exports = YouTubeSearch;
lib/ytmusicapi.js ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const axios = require('axios');
2
+
3
+ class YTMusic {
4
+ constructor() {
5
+ this.baseURL = 'https://music.youtube.com/youtubei/v1';
6
+ this.apiKey = 'AIzaSyC9XL3ZjWjXClIX1FmUxJq--EohcD4_oSs';
7
+ this.context = {
8
+ client: {
9
+ clientName: 'WEB_REMIX',
10
+ clientVersion: '1.20250915.03.00',
11
+ hl: 'en',
12
+ gl: 'US',
13
+ theme: 'MUSIC',
14
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
15
+ }
16
+ };
17
+ this.visitorData = null; // Will be captured from first response
18
+ }
19
+
20
+ async search(query, filter = null, continuationToken = null, ignoreSpelling = false) {
21
+ try {
22
+ const params = this._encodeSearchParams(query, filter, continuationToken, ignoreSpelling);
23
+ const response = await this._makeRequest('search', params);
24
+ return this._parseSearchResults(response);
25
+ } catch (error) {
26
+ throw new Error(`Search failed: ${error.message}`);
27
+ }
28
+ }
29
+
30
+ async getSearchSuggestions(query) {
31
+ try {
32
+ const params = {
33
+ input: query,
34
+ params: this._encodeSearchParams()
35
+ };
36
+
37
+ const response = await this._makeRequest('music/get_search_suggestions', params);
38
+ return this._parseSuggestions(response);
39
+ } catch (error) {
40
+ throw new Error(`Suggestions failed: ${error.message}`);
41
+ }
42
+ }
43
+
44
+ async getSong(videoId) {
45
+ try {
46
+ const params = {
47
+ videoId,
48
+ params: this._encodeVideoParams()
49
+ };
50
+
51
+ const response = await this._makeRequest('player', params);
52
+ return this._parseSongDetails(response);
53
+ } catch (error) {
54
+ throw new Error(`Song data unavailable: ${error.message}`);
55
+ }
56
+ }
57
+
58
+ async getAlbum(browseId) {
59
+ try {
60
+ const params = {
61
+ browseId,
62
+ context: this.context
63
+ };
64
+
65
+ const response = await this._makeRequest('browse', params);
66
+ return this._parseAlbumDetails(response);
67
+ } catch (error) {
68
+ throw new Error(`Album data unavailable: ${error.message}`);
69
+ }
70
+ }
71
+
72
+ async getArtist(browseId) {
73
+ try {
74
+ const params = {
75
+ browseId,
76
+ context: this.context
77
+ };
78
+
79
+ const response = await this._makeRequest('browse', params);
80
+ return this._parseArtistDetails(response);
81
+ } catch (error) {
82
+ throw new Error(`Artist data unavailable: ${error.message}`);
83
+ }
84
+ }
85
+
86
+ async getPlaylist(playlistId, limit = 100) {
87
+ try {
88
+ const params = {
89
+ playlistId,
90
+ params: this._encodePlaylistParams(limit)
91
+ };
92
+
93
+ const response = await this._makeRequest('browse', params);
94
+ return this._parsePlaylistDetails(response);
95
+ } catch (error) {
96
+ throw new Error(`Playlist data unavailable: ${error.message}`);
97
+ }
98
+ }
99
+
100
+ async getCharts(country = null) {
101
+ try {
102
+ const params = {
103
+ browseId: 'FEmusic_charts',
104
+ context: {
105
+ ...this.context,
106
+ client: {
107
+ ...this.context.client,
108
+ gl: country || 'US'
109
+ }
110
+ }
111
+ };
112
+
113
+ const response = await this._makeRequest('browse', params);
114
+ return this._parseChartsData(response);
115
+ } catch (error) {
116
+ throw new Error(`Charts data unavailable: ${error.message}`);
117
+ }
118
+ }
119
+
120
+ async getMoodCategories() {
121
+ try {
122
+ const params = {
123
+ browseId: 'FEmusic_moods_and_genres',
124
+ context: this.context
125
+ };
126
+
127
+ const response = await this._makeRequest('browse', params);
128
+ return this._parseMoodCategories(response);
129
+ } catch (error) {
130
+ throw new Error(`Mood categories unavailable: ${error.message}`);
131
+ }
132
+ }
133
+
134
+ async getMoodPlaylists(categoryId) {
135
+ try {
136
+ const params = {
137
+ browseId: categoryId,
138
+ context: this.context
139
+ };
140
+
141
+ const response = await this._makeRequest('browse', params);
142
+ return this._parseMoodPlaylists(response);
143
+ } catch (error) {
144
+ throw new Error(`Mood playlists unavailable: ${error.message}`);
145
+ }
146
+ }
147
+
148
+ async getWatchPlaylist(videoId = null, playlistId = null, radio = false, shuffle = false, limit = 25) {
149
+ try {
150
+ const params = {
151
+ videoId,
152
+ playlistId,
153
+ radio,
154
+ shuffle,
155
+ params: this._encodeWatchPlaylistParams(limit)
156
+ };
157
+
158
+ const response = await this._makeRequest('next', params);
159
+ return this._parseWatchPlaylist(response);
160
+ } catch (error) {
161
+ throw new Error(`Watch playlist unavailable: ${error.message}`);
162
+ }
163
+ }
164
+
165
+ // Private helper methods
166
+ async _makeRequest(endpoint, params) {
167
+ const url = `${this.baseURL}/${endpoint}?key=${this.apiKey}`;
168
+
169
+ let requestBody;
170
+
171
+ // Handle continuation tokens - they need ONLY context + continuation
172
+ if (params.continuation) {
173
+ requestBody = {
174
+ context: this.context,
175
+ continuation: params.continuation,
176
+ // Some backends require additional params mirroring web behavior
177
+ params: `&ctoken=${encodeURIComponent(params.continuation)}&continuation=${encodeURIComponent(params.continuation)}`
178
+ };
179
+ } else {
180
+ // For initial search requests
181
+ requestBody = {
182
+ context: this.context,
183
+ ...params
184
+ };
185
+ }
186
+
187
+ const response = await axios.post(url, requestBody, {
188
+ headers: {
189
+ 'User-Agent': this.context.client.userAgent,
190
+ 'Content-Type': 'application/json',
191
+ 'X-Goog-AuthUser': '0',
192
+ 'X-Origin': 'https://music.youtube.com',
193
+ // Prefer stable headers; only send visitor if previously learned
194
+ ...(this.visitorData ? { 'X-Goog-Visitor-Id': this.visitorData } : {}),
195
+ 'X-YouTube-Client-Name': '67', // WEB_REMIX
196
+ 'X-YouTube-Client-Version': this.context.client.clientVersion,
197
+ 'Accept': '*/*',
198
+ 'Accept-Language': 'en-US,en;q=0.9',
199
+ 'Referer': 'https://music.youtube.com'
200
+ }
201
+ });
202
+
203
+ // Capture stable visitorData from first successful call
204
+ try {
205
+ const vd = response?.data?.responseContext?.visitorData;
206
+ if (vd && !this.visitorData) this.visitorData = vd;
207
+ } catch {}
208
+
209
+ return response.data;
210
+ }
211
+
212
+ _generateVisitorId() {
213
+ // Deprecated: we now rely on server-provided visitorData
214
+ return null;
215
+ }
216
+
217
+ _encodeSearchParams(query, filter = null, continuationToken = null, ignoreSpelling = false) {
218
+ // If continuation token exists, return only the continuation
219
+ if (continuationToken) {
220
+ return {
221
+ continuation: continuationToken
222
+ };
223
+ }
224
+
225
+ // For initial search requests
226
+ const searchParams = {
227
+ query: query,
228
+ params: this._getFilterParams(filter)
229
+ };
230
+
231
+ if (ignoreSpelling) {
232
+ searchParams.params += '&ignore_spelling=true';
233
+ }
234
+
235
+ return searchParams;
236
+ }
237
+
238
+ _getFilterParams(filter) {
239
+ const filterMap = {
240
+ 'songs': 'Eg-KAQwIARAAGAAgACgAMABqChAEEAUQAxAKEAk%3D',
241
+ 'videos': 'Eg-KAQwIABABGAAgACgAMABqChAEEAUQAxAKEAk%3D',
242
+ 'albums': 'Eg-KAQwIABAAGAEgACgAMABqChAEEAUQAxAKEAk%3D',
243
+ 'artists': 'Eg-KAQwIAxAAGAAgACgAMABqChAEEAUQAxAKEAk%3D',
244
+ 'playlists': 'Eg-KAQwIABAAGAAgACgBMABqChAEEAUQAxAKEAk%3D',
245
+ 'profiles': 'Eg-KAQwIABABGAAgACgAMABqChAEEAUQAxAKEAk%3D',
246
+ 'podcasts': 'Eg-KAQwIABABGAAgACgAMABqChAEEAUQAxAKEAk%3D',
247
+ 'episodes': 'Eg-KAQwIABABGAAgACgAMABqChAEEAUQAxAKEAk%3D',
248
+ 'community_playlists': 'Eg-KAQwIABAAGAAgACgBMABqChAEEAUQAxAKEAk%3D'
249
+ };
250
+
251
+ return filterMap[filter] || 'Eg-KAQwIARAAGAAgACgAMABqChAEEAUQAxAKEAk%3D';
252
+ }
253
+
254
+ _encodeVideoParams() {
255
+ return Buffer.from(JSON.stringify({
256
+ videoId: '',
257
+ context: this.context
258
+ })).toString('base64');
259
+ }
260
+
261
+ _encodePlaylistParams(limit) {
262
+ return Buffer.from(JSON.stringify({
263
+ browseId: '',
264
+ params: `6gPTAUNwc0JBRUNBQ0F%3D&limit=${limit}`
265
+ })).toString('base64');
266
+ }
267
+
268
+ _encodeWatchPlaylistParams(limit) {
269
+ return Buffer.from(JSON.stringify({
270
+ videoId: '',
271
+ playlistId: '',
272
+ radio: false,
273
+ shuffle: false,
274
+ params: `6gPTAUNwc0JBRUNBQ0F%3D&limit=${limit}`
275
+ })).toString('base64');
276
+ }
277
+
278
+ _parseSearchResults(data) {
279
+ const results = [];
280
+ let continuationToken = null;
281
+
282
+ // 1) continuationContents (various keys)
283
+ if (data?.continuationContents) {
284
+ const cc = data.continuationContents;
285
+ for (const key of Object.keys(cc)) {
286
+ const block = cc[key];
287
+ const contents = block?.contents || [];
288
+ for (const entry of contents) {
289
+ if (entry.musicShelfRenderer) {
290
+ const shelfItems = entry.musicShelfRenderer.contents || [];
291
+ for (const si of shelfItems) {
292
+ const m = si.musicResponsiveListItemRenderer;
293
+ if (m) {
294
+ const parsed = this._parseMusicItem(m);
295
+ if (parsed) results.push(parsed);
296
+ }
297
+ }
298
+ const cont = entry.musicShelfRenderer?.continuations?.[0];
299
+ continuationToken = cont?.nextContinuationData?.continuation
300
+ || cont?.reloadContinuationData?.continuation
301
+ || continuationToken;
302
+ } else if (entry.musicResponsiveListItemRenderer) {
303
+ const parsed = this._parseMusicItem(entry.musicResponsiveListItemRenderer);
304
+ if (parsed) results.push(parsed);
305
+ } else if (entry.continuationItemRenderer) {
306
+ continuationToken = entry.continuationItemRenderer?.continuationEndpoint?.continuationCommand?.token || continuationToken;
307
+ }
308
+ }
309
+ }
310
+ }
311
+
312
+ // 2) onResponseReceived* (append or reload)
313
+ const actions = data?.onResponseReceivedActions || data?.onResponseReceivedCommands || [];
314
+ for (const action of actions) {
315
+ const append = action?.appendContinuationItemsAction;
316
+ const reload = action?.reloadContinuationItemsCommand;
317
+ const items = append?.continuationItems || reload?.continuationItems || [];
318
+ for (const entry of items) {
319
+ if (entry.musicShelfContinuation) {
320
+ // Continuation node directly
321
+ const shelfItems = entry.musicShelfContinuation.contents || [];
322
+ for (const si of shelfItems) {
323
+ const m = si.musicResponsiveListItemRenderer;
324
+ if (m) {
325
+ const parsed = this._parseMusicItem(m);
326
+ if (parsed) results.push(parsed);
327
+ }
328
+ }
329
+ const cont = entry.musicShelfContinuation?.continuations?.[0];
330
+ continuationToken = cont?.nextContinuationData?.continuation
331
+ || cont?.reloadContinuationData?.continuation
332
+ || continuationToken;
333
+ } else if (entry.musicShelfRenderer) {
334
+ const shelfItems = entry.musicShelfRenderer.contents || [];
335
+ for (const si of shelfItems) {
336
+ const m = si.musicResponsiveListItemRenderer;
337
+ if (m) {
338
+ const parsed = this._parseMusicItem(m);
339
+ if (parsed) results.push(parsed);
340
+ }
341
+ }
342
+ const cont = entry.musicShelfRenderer?.continuations?.[0];
343
+ continuationToken = cont?.nextContinuationData?.continuation
344
+ || cont?.reloadContinuationData?.continuation
345
+ || continuationToken;
346
+ } else if (entry.musicResponsiveListItemRenderer) {
347
+ const parsed = this._parseMusicItem(entry.musicResponsiveListItemRenderer);
348
+ if (parsed) results.push(parsed);
349
+ } else if (entry.continuationItemRenderer) {
350
+ continuationToken = entry.continuationItemRenderer?.continuationEndpoint?.continuationCommand?.token || continuationToken;
351
+ }
352
+ }
353
+ }
354
+
355
+ // 3) initial contents
356
+ if (results.length === 0) {
357
+ const initial = data?.contents?.tabbedSearchResultsRenderer?.tabs?.[0]?.tabRenderer?.content?.sectionListRenderer?.contents || [];
358
+ for (const section of initial) {
359
+ if (section.musicShelfRenderer) {
360
+ const items = section.musicShelfRenderer.contents || [];
361
+ for (const it of items) {
362
+ const m = it.musicResponsiveListItemRenderer;
363
+ if (m) {
364
+ const parsed = this._parseMusicItem(m);
365
+ if (parsed) results.push(parsed);
366
+ }
367
+ }
368
+ const cont = section.musicShelfRenderer?.continuations?.[0];
369
+ continuationToken = cont?.nextContinuationData?.continuation
370
+ || cont?.reloadContinuationData?.continuation
371
+ || continuationToken;
372
+ }
373
+ if (section.continuationItemRenderer) {
374
+ continuationToken = section.continuationItemRenderer?.continuationEndpoint?.continuationCommand?.token || continuationToken;
375
+ }
376
+ }
377
+ }
378
+
379
+ return { results, continuationToken };
380
+ }
381
+
382
+ _parseSuggestions(data) {
383
+ const suggestions = [];
384
+ const contents = data?.contents || [];
385
+
386
+ contents.forEach(content => {
387
+ const runs = content?.searchSuggestionRenderer?.suggestion?.runs || [];
388
+ let suggestionText = '';
389
+ runs.forEach(run => {
390
+ if (run.text) {
391
+ suggestionText += run.text;
392
+ }
393
+ });
394
+ if (suggestionText) {
395
+ suggestions.push(suggestionText);
396
+ }
397
+ });
398
+
399
+ return suggestions;
400
+ }
401
+
402
+ _parseSongDetails(data) {
403
+ const videoDetails = data?.videoDetails || {};
404
+ const microformat = data?.microformat?.microformatDataRenderer || {};
405
+
406
+ return {
407
+ videoId: videoDetails.videoId,
408
+ title: videoDetails.title,
409
+ author: videoDetails.author,
410
+ lengthSeconds: videoDetails.lengthSeconds,
411
+ thumbnail: videoDetails.thumbnail?.thumbnails?.[0]?.url,
412
+ description: microformat.description,
413
+ category: microformat.category
414
+ };
415
+ }
416
+
417
+ _parseAlbumDetails(data) {
418
+ const header = data?.header?.musicDetailHeaderRenderer || data?.header?.musicImmersiveHeaderRenderer || {};
419
+ const contents = data?.contents?.singleColumnBrowseResultsRenderer?.tabs?.[0]?.tabRenderer?.content?.sectionListRenderer?.contents || [];
420
+
421
+ return {
422
+ title: header.title?.runs?.[0]?.text,
423
+ artist: header.subtitle?.runs?.[0]?.text,
424
+ thumbnail: header.thumbnail?.musicThumbnailRenderer?.thumbnail?.thumbnails?.[0]?.url,
425
+ tracks: this._parseTracksFromContents(contents)
426
+ };
427
+ }
428
+
429
+ _parseArtistDetails(data) {
430
+ const header = data?.header?.musicImmersiveHeaderRenderer || data?.header?.musicVisualHeaderRenderer || {};
431
+ const contents = data?.contents?.singleColumnBrowseResultsRenderer?.tabs?.[0]?.tabRenderer?.content?.sectionListRenderer?.contents || [];
432
+
433
+ return {
434
+ name: header.title?.runs?.[0]?.text,
435
+ description: header.description?.runs?.[0]?.text,
436
+ thumbnail: header.thumbnail?.musicThumbnailRenderer?.thumbnail?.thumbnails?.[0]?.url,
437
+ albums: this._parseAlbumsFromContents(contents),
438
+ singles: this._parseSinglesFromContents(contents)
439
+ };
440
+ }
441
+
442
+ _parsePlaylistDetails(data) {
443
+ const header = data?.header?.musicDetailHeaderRenderer || {};
444
+ const contents = data?.contents?.singleColumnBrowseResultsRenderer?.tabs?.[0]?.tabRenderer?.content?.sectionListRenderer?.contents || [];
445
+
446
+ return {
447
+ title: header.title?.runs?.[0]?.text,
448
+ author: header.subtitle?.runs?.[0]?.text,
449
+ thumbnail: header.thumbnail?.musicThumbnailRenderer?.thumbnail?.thumbnails?.[0]?.url,
450
+ tracks: this._parseTracksFromContents(contents)
451
+ };
452
+ }
453
+
454
+ _parseChartsData(data) {
455
+ const contents = data?.contents?.singleColumnBrowseResultsRenderer?.tabs?.[0]?.tabRenderer?.content?.sectionListRenderer?.contents || [];
456
+ const charts = [];
457
+
458
+ contents.forEach(section => {
459
+ if (section.musicShelfRenderer) {
460
+ const title = section.musicShelfRenderer.title?.runs?.[0]?.text;
461
+ const items = section.musicShelfRenderer.contents || [];
462
+ const chartItems = items.map(item => this._parseMusicItem(item.musicResponsiveListItemRenderer)).filter(Boolean);
463
+
464
+ charts.push({
465
+ title,
466
+ items: chartItems
467
+ });
468
+ }
469
+ });
470
+
471
+ return charts;
472
+ }
473
+
474
+ _parseMoodCategories(data) {
475
+ const contents = data?.contents?.singleColumnBrowseResultsRenderer?.tabs?.[0]?.tabRenderer?.content?.sectionListRenderer?.contents || [];
476
+ const categories = [];
477
+
478
+ contents.forEach(section => {
479
+ if (section.musicCarouselShelfRenderer) {
480
+ const title = section.musicCarouselShelfRenderer.header?.musicCarouselShelfBasicHeaderRenderer?.title?.runs?.[0]?.text;
481
+ const items = section.musicCarouselShelfRenderer.contents || [];
482
+ const categoryItems = items.map(item => this._parseMusicItem(item.musicTwoRowItemRenderer)).filter(Boolean);
483
+
484
+ categories.push({
485
+ title,
486
+ items: categoryItems
487
+ });
488
+ }
489
+ });
490
+
491
+ return categories;
492
+ }
493
+
494
+ _parseMoodPlaylists(data) {
495
+ const contents = data?.contents?.singleColumnBrowseResultsRenderer?.tabs?.[0]?.tabRenderer?.content?.sectionListRenderer?.contents || [];
496
+ const playlists = [];
497
+
498
+ contents.forEach(section => {
499
+ if (section.musicShelfRenderer) {
500
+ const items = section.musicShelfRenderer.contents || [];
501
+ const playlistItems = items.map(item => this._parseMusicItem(item.musicResponsiveListItemRenderer)).filter(Boolean);
502
+ playlists.push(...playlistItems);
503
+ }
504
+ });
505
+
506
+ return playlists;
507
+ }
508
+
509
+ _parseWatchPlaylist(data) {
510
+ const contents = data?.contents?.singleColumnMusicWatchNextResultsRenderer?.tabbedRenderer?.watchNextTabbedResultsRenderer?.tabs?.[0]?.tabRenderer?.content?.musicQueueRenderer?.content?.playlistPanelRenderer?.contents || [];
511
+ const tracks = [];
512
+
513
+ contents.forEach(item => {
514
+ if (item.playlistPanelVideoRenderer) {
515
+ const video = item.playlistPanelVideoRenderer;
516
+ tracks.push({
517
+ videoId: video.videoId,
518
+ title: video.title?.runs?.[0]?.text,
519
+ author: video.shortBylineText?.runs?.[0]?.text,
520
+ lengthSeconds: video.lengthSeconds,
521
+ thumbnail: video.thumbnail?.thumbnails?.[0]?.url
522
+ });
523
+ }
524
+ });
525
+
526
+ return {
527
+ tracks,
528
+ playlistId: data?.watchNextRenderer?.playlistId
529
+ };
530
+ }
531
+
532
+ _parseMusicItem(item) {
533
+ if (!item) return null;
534
+
535
+ const title = item.flexColumns?.[0]?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.[0]?.text;
536
+ const subtitle = item.flexColumns?.[1]?.musicResponsiveListItemFlexColumnRenderer?.text?.runs || [];
537
+ const thumbnail = item.thumbnail?.musicThumbnailRenderer?.thumbnail?.thumbnails?.[0]?.url;
538
+
539
+ const videoId = item.overlay?.musicItemThumbnailOverlayRenderer?.content?.musicPlayButtonRenderer?.playNavigationEndpoint?.watchEndpoint?.videoId;
540
+ const browseId = item.navigationEndpoint?.browseEndpoint?.browseId;
541
+ const playlistId = item.navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType === 'MUSIC_PAGE_TYPE_PLAYLIST'
542
+ ? item.navigationEndpoint?.browseEndpoint?.browseId
543
+ : null;
544
+
545
+ const duration = item.fixedColumns?.[0]?.musicResponsiveListItemFixedColumnRenderer?.text?.runs?.[0]?.text;
546
+
547
+ const artists = [];
548
+ let album = null;
549
+ let views = null;
550
+ let year = null;
551
+
552
+ subtitle.forEach((run, index) => {
553
+ if (run.navigationEndpoint?.browseEndpoint) {
554
+ const pageType = run.navigationEndpoint.browseEndpoint.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType;
555
+
556
+ if (pageType === 'MUSIC_PAGE_TYPE_ARTIST') {
557
+ artists.push({
558
+ name: run.text,
559
+ id: run.navigationEndpoint.browseEndpoint.browseId
560
+ });
561
+ } else if (pageType === 'MUSIC_PAGE_TYPE_ALBUM') {
562
+ album = {
563
+ name: run.text,
564
+ id: run.navigationEndpoint.browseEndpoint.browseId
565
+ };
566
+ }
567
+ } else if (run.text) {
568
+ const text = run.text.trim();
569
+ if (text.includes('views')) {
570
+ views = text;
571
+ } else if (/^\d{4}$/.test(text)) {
572
+ year = text;
573
+ }
574
+ }
575
+ });
576
+
577
+ const isExplicit = item.badges?.some(badge =>
578
+ badge.musicInlineBadgeRenderer?.icon?.iconType === 'MUSIC_EXPLICIT_BADGE'
579
+ ) || false;
580
+
581
+ let resultType = 'song';
582
+ let category = 'Songs';
583
+
584
+ if (playlistId) {
585
+ resultType = 'playlist';
586
+ category = 'Playlists';
587
+ } else if (browseId?.startsWith('UC')) {
588
+ resultType = 'artist';
589
+ category = 'Artists';
590
+ } else if (browseId?.startsWith('MPREb_')) {
591
+ resultType = 'album';
592
+ category = 'Albums';
593
+ }
594
+
595
+ const result = {
596
+ category: category,
597
+ resultType: resultType,
598
+ title: title,
599
+ thumbnails: this._parseThumbnails(item.thumbnail?.musicThumbnailRenderer?.thumbnail?.thumbnails || []),
600
+ isExplicit: isExplicit
601
+ };
602
+
603
+ if (videoId) {
604
+ result.videoId = videoId;
605
+ result.duration = duration;
606
+ result.duration_seconds = this._parseDurationToSeconds(duration);
607
+ result.videoType = 'MUSIC_VIDEO_TYPE_ATV';
608
+ }
609
+
610
+ if (artists.length > 0) {
611
+ result.artists = artists;
612
+ }
613
+
614
+ if (album) {
615
+ result.album = album;
616
+ }
617
+
618
+ if (browseId) {
619
+ result.browseId = browseId;
620
+ }
621
+
622
+ if (views) {
623
+ result.views = views;
624
+ }
625
+
626
+ if (year) {
627
+ result.year = year;
628
+ }
629
+
630
+ return result;
631
+ }
632
+
633
+ _parseDurationToSeconds(duration) {
634
+ if (!duration) return null;
635
+
636
+ const parts = duration.split(':').map(p => parseInt(p));
637
+ if (parts.length === 3) {
638
+ return parts[0] * 3600 + parts[1] * 60 + parts[2];
639
+ } else if (parts.length === 2) {
640
+ return parts[0] * 60 + parts[1];
641
+ } else if (parts.length === 1) {
642
+ return parts[0];
643
+ }
644
+ return null;
645
+ }
646
+
647
+ _parseThumbnails(thumbnails) {
648
+ return thumbnails.map(thumb => ({
649
+ url: thumb.url,
650
+ width: thumb.width,
651
+ height: thumb.height
652
+ }));
653
+ }
654
+
655
+ _parseTracksFromContents(contents) {
656
+ const tracks = [];
657
+
658
+ contents.forEach(section => {
659
+ if (section.musicShelfRenderer) {
660
+ const items = section.musicShelfRenderer.contents || [];
661
+ items.forEach(item => {
662
+ if (item.musicResponsiveListItemRenderer) {
663
+ const track = this._parseMusicItem(item.musicResponsiveListItemRenderer);
664
+ if (track) tracks.push(track);
665
+ }
666
+ });
667
+ }
668
+ });
669
+
670
+ return tracks;
671
+ }
672
+
673
+ _parseAlbumsFromContents(contents) {
674
+ return this._parseTracksFromContents(contents);
675
+ }
676
+
677
+ _parseSinglesFromContents(contents) {
678
+ return this._parseTracksFromContents(contents);
679
+ }
680
+ }
681
+
682
+ module.exports = YTMusic;
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "music-api-js",
3
+ "version": "1.0.0",
4
+ "description": "Node.js version of the Music API with YouTube Music, YouTube Search, and JioSaavn integration",
5
+ "main": "app.js",
6
+ "scripts": {
7
+ "start": "node app.js",
8
+ "dev": "nodemon app.js",
9
+ "test": "jest"
10
+ },
11
+ "keywords": ["music", "api", "youtube", "jiosaavn", "nodejs", "express"],
12
+ "author": "Your Name",
13
+ "license": "MIT",
14
+ "dependencies": {
15
+ "express": "^4.18.2",
16
+ "cors": "^2.8.5",
17
+ "axios": "^1.6.0",
18
+ "swagger-jsdoc": "^6.2.8",
19
+ "swagger-ui-express": "^5.0.0",
20
+ "dotenv": "^16.3.1",
21
+ "helmet": "^7.1.0",
22
+ "morgan": "^1.10.0"
23
+ },
24
+ "devDependencies": {
25
+ "nodemon": "^3.0.1",
26
+ "jest": "^29.7.0"
27
+ },
28
+ "engines": {
29
+ "node": ">=16.0.0"
30
+ }
31
+ }
routes/.DS_Store ADDED
Binary file (6.15 kB). View file
 
routes/api.js ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+
3
+ const router = express.Router();
4
+
5
+ const ALLOWED_FILTERS = new Set([
6
+ 'songs',
7
+ 'videos',
8
+ 'albums',
9
+ 'artists',
10
+ 'playlists',
11
+ 'profiles',
12
+ 'podcasts',
13
+ 'episodes',
14
+ 'community_playlists'
15
+ ]);
16
+
17
+ /**
18
+ * @swagger
19
+ * /api/search:
20
+ * get:
21
+ * summary: Search YouTube Music
22
+ * parameters:
23
+ * - in: query
24
+ * name: q
25
+ * required: true
26
+ * schema:
27
+ * type: string
28
+ * description: Search query string
29
+ * - in: query
30
+ * name: filter
31
+ * schema:
32
+ * type: string
33
+ * enum: [songs, videos, albums, artists, playlists, profiles, podcasts, episodes, community_playlists]
34
+ * description: Restrict results to a specific type
35
+ * - in: query
36
+ * name: continuationToken
37
+ * schema:
38
+ * type: string
39
+ * description: Continuation token for pagination
40
+ * - in: query
41
+ * name: ignore_spelling
42
+ * schema:
43
+ * type: boolean
44
+ * default: false
45
+ * description: Whether to ignore spelling corrections
46
+ * responses:
47
+ * 200:
48
+ * description: Search results with continuation token
49
+ * 400:
50
+ * description: Missing/invalid params
51
+ */
52
+ router.get('/search', async (req, res) => {
53
+ try {
54
+ const { q: query, filter, continuationToken, ignore_spelling = false } = req.query;
55
+
56
+ // FIXED: Don't require query if continuation token is provided
57
+ if (!query && !continuationToken) {
58
+ return res.status(400).json({ error: "Missing required query parameter 'q' or 'continuationToken'" });
59
+ }
60
+
61
+ if (filter && !ALLOWED_FILTERS.has(filter)) {
62
+ return res.status(400).json({
63
+ error: `Invalid filter. Allowed: ${Array.from(ALLOWED_FILTERS).sort()}`
64
+ });
65
+ }
66
+
67
+ const ytmusic = req.app.locals.ytmusic;
68
+
69
+ // FIXED: Pass query only if it's not a continuation request
70
+ const searchResults = await ytmusic.search(
71
+ query || null,
72
+ filter,
73
+ continuationToken,
74
+ ignore_spelling === 'true'
75
+ );
76
+
77
+ res.json({
78
+ query: query || null,
79
+ filter,
80
+ results: searchResults.results,
81
+ continuationToken: searchResults.continuationToken
82
+ });
83
+ } catch (error) {
84
+ console.error('Search error:', error);
85
+ res.status(500).json({ error: `Search failed: ${error.message}` });
86
+ }
87
+ });
88
+
89
+ /**
90
+ * @swagger
91
+ * /api/search/suggestions:
92
+ * get:
93
+ * summary: Get search suggestions
94
+ * parameters:
95
+ * - in: query
96
+ * name: q
97
+ * required: true
98
+ * schema:
99
+ * type: string
100
+ * description: Partial query to get suggestions for
101
+ * - in: query
102
+ * name: music
103
+ * schema:
104
+ * type: integer
105
+ * description: If 1, get suggestions from YouTube Music. If not present or 0, get suggestions from YouTube
106
+ * responses:
107
+ * 200:
108
+ * description: Suggestions
109
+ * 400:
110
+ * description: Missing/invalid params
111
+ */
112
+ router.get('/search/suggestions', async (req, res) => {
113
+ try {
114
+ const { q: query, music } = req.query;
115
+
116
+ if (!query) {
117
+ return res.status(400).json({ error: "Missing required query parameter 'q'" });
118
+ }
119
+
120
+ const ytmusic = req.app.locals.ytmusic;
121
+ const youtubeSearch = req.app.locals.youtubeSearch;
122
+
123
+ if (music === '1') {
124
+ // Get suggestions from YouTube Music
125
+ const suggestions = await ytmusic.getSearchSuggestions(query);
126
+ res.json({ suggestions, source: 'youtube_music' });
127
+ } else {
128
+ // Get suggestions from YouTube
129
+ const suggestions = await youtubeSearch.getSuggestions(query);
130
+ res.json({ suggestions, source: 'youtube' });
131
+ }
132
+ } catch (error) {
133
+ console.error('Suggestions error:', error);
134
+ res.status(500).json({ error: `Suggestions failed: ${error.message}` });
135
+ }
136
+ });
137
+
138
+ /**
139
+ * @swagger
140
+ * /api/search/suggestions/debug:
141
+ * get:
142
+ * summary: Debug endpoint to test YouTube suggestions API directly
143
+ * parameters:
144
+ * - in: query
145
+ * name: q
146
+ * required: true
147
+ * schema:
148
+ * type: string
149
+ * description: Query to test
150
+ * responses:
151
+ * 200:
152
+ * description: Debug suggestions
153
+ * 400:
154
+ * description: Missing query parameter
155
+ */
156
+ router.get('/search/suggestions/debug', async (req, res) => {
157
+ try {
158
+ const { q: query } = req.query;
159
+
160
+ if (!query) {
161
+ return res.status(400).json({ error: "Missing required query parameter 'q'" });
162
+ }
163
+
164
+ const youtubeSearch = req.app.locals.youtubeSearch;
165
+ const suggestions = await youtubeSearch.getSuggestions(query);
166
+
167
+ res.json({
168
+ query,
169
+ suggestions,
170
+ count: suggestions.length,
171
+ source: 'youtube_debug'
172
+ });
173
+ } catch (error) {
174
+ console.error('Debug suggestions error:', error);
175
+ res.status(500).json({
176
+ error: `Debug failed: ${error.message}`,
177
+ query: req.query.q
178
+ });
179
+ }
180
+ });
181
+
182
+ module.exports = router;
routes/entities.js ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const axios = require('axios');
3
+ const router = express.Router();
4
+
5
+ /**
6
+ * @swagger
7
+ * /api/songs/{videoId}:
8
+ * get:
9
+ * summary: Get song details
10
+ * parameters:
11
+ * - in: path
12
+ * name: videoId
13
+ * required: true
14
+ * schema:
15
+ * type: string
16
+ * description: YouTube video ID
17
+ * responses:
18
+ * 200:
19
+ * description: Song metadata
20
+ * 500:
21
+ * description: Song data unavailable
22
+ */
23
+ router.get('/songs/:videoId', async (req, res) => {
24
+ try {
25
+ const { videoId } = req.params;
26
+ const ytmusic = req.app.locals.ytmusic;
27
+
28
+ const data = await ytmusic.getSong(videoId);
29
+ res.json(data);
30
+ } catch (error) {
31
+ console.error('Song error:', error);
32
+ res.status(500).json({ error: `Song data unavailable: ${error.message}` });
33
+ }
34
+ });
35
+
36
+ /**
37
+ * @swagger
38
+ * /api/albums/{browseId}:
39
+ * get:
40
+ * summary: Get album details
41
+ * parameters:
42
+ * - in: path
43
+ * name: browseId
44
+ * required: true
45
+ * schema:
46
+ * type: string
47
+ * description: Album browse ID
48
+ * responses:
49
+ * 200:
50
+ * description: Album metadata and tracks
51
+ * 500:
52
+ * description: Album data unavailable
53
+ */
54
+ router.get('/albums/:browseId', async (req, res) => {
55
+ try {
56
+ const { browseId } = req.params;
57
+ const ytmusic = req.app.locals.ytmusic;
58
+
59
+ const data = await ytmusic.getAlbum(browseId);
60
+ res.json(data);
61
+ } catch (error) {
62
+ console.error('Album error:', error);
63
+ res.status(500).json({ error: `Album data unavailable: ${error.message}` });
64
+ }
65
+ });
66
+
67
+ /**
68
+ * @swagger
69
+ * /api/artists/{browseId}:
70
+ * get:
71
+ * summary: Get artist details
72
+ * parameters:
73
+ * - in: path
74
+ * name: browseId
75
+ * required: true
76
+ * schema:
77
+ * type: string
78
+ * description: Artist browse ID
79
+ * responses:
80
+ * 200:
81
+ * description: Artist info and releases
82
+ * 500:
83
+ * description: Artist data unavailable
84
+ */
85
+ router.get('/artists/:browseId', async (req, res) => {
86
+ try {
87
+ const { browseId } = req.params;
88
+ const ytmusic = req.app.locals.ytmusic;
89
+
90
+ const data = await ytmusic.getArtist(browseId);
91
+ res.json(data);
92
+ } catch (error) {
93
+ console.error('Artist error:', error);
94
+ res.status(500).json({ error: `Artist data unavailable: ${error.message}` });
95
+ }
96
+ });
97
+
98
+ /**
99
+ * @swagger
100
+ * /api/playlists/{playlistId}:
101
+ * get:
102
+ * summary: Get playlist details
103
+ * parameters:
104
+ * - in: path
105
+ * name: playlistId
106
+ * required: true
107
+ * schema:
108
+ * type: string
109
+ * description: Playlist ID
110
+ * - in: query
111
+ * name: limit
112
+ * schema:
113
+ * type: integer
114
+ * default: 100
115
+ * description: Maximum number of tracks
116
+ * responses:
117
+ * 200:
118
+ * description: Playlist metadata and items
119
+ * 500:
120
+ * description: Playlist data unavailable
121
+ */
122
+ router.get('/playlists/:playlistId', async (req, res) => {
123
+ try {
124
+ const { playlistId } = req.params;
125
+ const { limit = 100 } = req.query;
126
+ const ytmusic = req.app.locals.ytmusic;
127
+
128
+ const data = await ytmusic.getPlaylist(playlistId, parseInt(limit));
129
+ res.json(data);
130
+ } catch (error) {
131
+ console.error('Playlist error:', error);
132
+ res.status(500).json({ error: `Playlist data unavailable: ${error.message}` });
133
+ }
134
+ });
135
+
136
+ /**
137
+ * @swagger
138
+ * /api/artist/{artistId}:
139
+ * get:
140
+ * summary: Get artist summary via youtubei browse (Top songs, recommendations, featured-on)
141
+ * parameters:
142
+ * - in: path
143
+ * name: artistId
144
+ * required: true
145
+ * schema:
146
+ * type: string
147
+ * description: Artist ID
148
+ * - in: query
149
+ * name: country
150
+ * schema:
151
+ * type: string
152
+ * default: US
153
+ * description: Country code
154
+ * responses:
155
+ * 200:
156
+ * description: Artist summary payload
157
+ * 500:
158
+ * description: Artist data unavailable
159
+ */
160
+ router.get('/artist/:artistId', async (req, res) => {
161
+ try {
162
+ const { artistId } = req.params;
163
+ const { country = 'US' } = req.query;
164
+
165
+ const YOUTUBE_MUSIC_API_URL = 'https://summer-darkness-1435.bob17040246.workers.dev/youtubei/v1/browse?prettyPrint=false';
166
+
167
+ const body = {
168
+ browseId: artistId,
169
+ context: {
170
+ client: {
171
+ clientName: 'WEB_REMIX',
172
+ clientVersion: '1.20250915.03.00',
173
+ gl: country
174
+ }
175
+ }
176
+ };
177
+
178
+ const response = await axios.post(YOUTUBE_MUSIC_API_URL, body, {
179
+ headers: { 'Content-Type': 'application/json' },
180
+ timeout: 15000
181
+ });
182
+
183
+ if (response.status !== 200) {
184
+ return res.status(500).json({ error: `HTTP error: ${response.status}` });
185
+ }
186
+
187
+ const data = response.data;
188
+
189
+ // Parse like the Python logic
190
+ const contents = data?.contents?.singleColumnBrowseResultsRenderer?.tabs?.[0]?.tabRenderer?.content?.sectionListRenderer?.contents || [];
191
+ const artistHeader = data?.header?.musicImmersiveHeaderRenderer?.title?.runs?.[0]?.text;
192
+
193
+ // Top songs shelf
194
+ let playlistId = null;
195
+ for (const item of contents) {
196
+ if (item.musicShelfRenderer) {
197
+ const titleRuns = item.musicShelfRenderer.title?.runs || [];
198
+ if (titleRuns[0]?.text === 'Top songs') {
199
+ try {
200
+ playlistId = item.musicShelfRenderer.contents?.[0]?.musicResponsiveListItemRenderer?.flexColumns?.[0]?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.[0]?.navigationEndpoint?.watchEndpoint?.playlistId;
201
+ } catch (e) {
202
+ playlistId = null;
203
+ }
204
+ break;
205
+ }
206
+ }
207
+ }
208
+
209
+ // Recommended artists
210
+ let recommendedArtists = null;
211
+ for (const item of contents) {
212
+ if (item.musicCarouselShelfRenderer) {
213
+ const header = item.musicCarouselShelfRenderer.header?.musicCarouselShelfBasicHeaderRenderer;
214
+ const headerTitle = header?.title?.runs?.[0]?.text;
215
+ if (headerTitle === 'Fans might also like') {
216
+ recommendedArtists = [];
217
+ for (const it of item.musicCarouselShelfRenderer.contents || []) {
218
+ const twoRow = it.musicTwoRowItemRenderer;
219
+ if (twoRow) {
220
+ recommendedArtists.push({
221
+ name: twoRow.title?.runs?.[0]?.text,
222
+ browseId: twoRow.navigationEndpoint?.browseEndpoint?.browseId,
223
+ thumbnail: twoRow.thumbnailRenderer?.musicThumbnailRenderer?.thumbnail?.thumbnails?.[0]?.url
224
+ });
225
+ }
226
+ }
227
+ break;
228
+ }
229
+ }
230
+ }
231
+
232
+ // Featured on
233
+ let featuredOnPlaylists = null;
234
+ for (const item of contents) {
235
+ if (item.musicCarouselShelfRenderer) {
236
+ const header = item.musicCarouselShelfRenderer.header?.musicCarouselShelfBasicHeaderRenderer;
237
+ const headerTitle = header?.title?.runs?.[0]?.text;
238
+ if (headerTitle === 'Featured on') {
239
+ featuredOnPlaylists = [];
240
+ for (const it of item.musicCarouselShelfRenderer.contents || []) {
241
+ const twoRow = it.musicTwoRowItemRenderer;
242
+ if (twoRow) {
243
+ featuredOnPlaylists.push({
244
+ title: twoRow.title?.runs?.[0]?.text,
245
+ browseId: twoRow.navigationEndpoint?.browseEndpoint?.browseId,
246
+ thumbnail: twoRow.thumbnailRenderer?.musicThumbnailRenderer?.thumbnail?.thumbnails?.[0]?.url
247
+ });
248
+ }
249
+ }
250
+ break;
251
+ }
252
+ }
253
+ }
254
+
255
+ res.json({
256
+ artistName: artistHeader,
257
+ playlistId,
258
+ recommendedArtists,
259
+ featuredOnPlaylists
260
+ });
261
+ } catch (error) {
262
+ console.error('Artist summary error:', error);
263
+ res.status(500).json({ error: `Artist data unavailable: ${error.message}` });
264
+ }
265
+ });
266
+
267
+ module.exports = router;
routes/explore.js ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const router = express.Router();
3
+
4
+ /**
5
+ * @swagger
6
+ * /api/charts:
7
+ * get:
8
+ * summary: Get charts (global or by country)
9
+ * parameters:
10
+ * - in: query
11
+ * name: country
12
+ * schema:
13
+ * type: string
14
+ * description: Country code
15
+ * responses:
16
+ * 200:
17
+ * description: Charts data
18
+ * 500:
19
+ * description: Charts data unavailable
20
+ */
21
+ router.get('/charts', async (req, res) => {
22
+ try {
23
+ const { country } = req.query;
24
+ const ytmusic = req.app.locals.ytmusic;
25
+
26
+ const data = await ytmusic.getCharts(country);
27
+ res.json(data);
28
+ } catch (error) {
29
+ console.error('Charts error:', error);
30
+ const errorMsg = error.message || 'Charts service temporarily unavailable';
31
+ res.status(500).json({
32
+ error: `Charts data unavailable: ${errorMsg}`,
33
+ message: 'YouTube Music charts are currently not accessible. This may be due to regional restrictions or service limitations.',
34
+ fallback: 'Try using the search endpoint instead: /api/search?q=trending&filter=songs'
35
+ });
36
+ }
37
+ });
38
+
39
+ /**
40
+ * @swagger
41
+ * /api/moods:
42
+ * get:
43
+ * summary: Get mood/genre categories
44
+ * responses:
45
+ * 200:
46
+ * description: Mood categories
47
+ * 500:
48
+ * description: Mood categories unavailable
49
+ */
50
+ router.get('/moods', async (req, res) => {
51
+ try {
52
+ const ytmusic = req.app.locals.ytmusic;
53
+ const data = await ytmusic.getMoodCategories();
54
+ res.json(data);
55
+ } catch (error) {
56
+ console.error('Moods error:', error);
57
+ const errorMsg = error.message || 'Mood categories service temporarily unavailable';
58
+ res.status(500).json({
59
+ error: `Mood categories unavailable: ${errorMsg}`,
60
+ message: 'YouTube Music mood categories are currently not accessible.',
61
+ fallback: 'Try using the search endpoint instead: /api/search?q=relaxing&filter=playlists'
62
+ });
63
+ }
64
+ });
65
+
66
+ /**
67
+ * @swagger
68
+ * /api/moods/{categoryId}:
69
+ * get:
70
+ * summary: Get playlists for a mood/genre category
71
+ * parameters:
72
+ * - in: path
73
+ * name: categoryId
74
+ * required: true
75
+ * schema:
76
+ * type: string
77
+ * description: Category ID
78
+ * responses:
79
+ * 200:
80
+ * description: Mood playlists
81
+ * 500:
82
+ * description: Mood playlists unavailable
83
+ */
84
+ router.get('/moods/:categoryId', async (req, res) => {
85
+ try {
86
+ const { categoryId } = req.params;
87
+ const ytmusic = req.app.locals.ytmusic;
88
+
89
+ const data = await ytmusic.getMoodPlaylists(categoryId);
90
+ res.json(data);
91
+ } catch (error) {
92
+ console.error('Mood playlists error:', error);
93
+ const errorMsg = error.message || 'Mood playlists service temporarily unavailable';
94
+ res.status(500).json({
95
+ error: `Mood playlists unavailable: ${errorMsg}`,
96
+ message: `Mood playlists for category '${req.params.categoryId}' are currently not accessible.`,
97
+ fallback: 'Try using the search endpoint instead: /api/search?q=mood&filter=playlists'
98
+ });
99
+ }
100
+ });
101
+
102
+ /**
103
+ * @swagger
104
+ * /api/watch_playlist:
105
+ * get:
106
+ * summary: Get watch playlist (radio/shuffle)
107
+ * parameters:
108
+ * - in: query
109
+ * name: videoId
110
+ * schema:
111
+ * type: string
112
+ * description: Video ID
113
+ * - in: query
114
+ * name: playlistId
115
+ * schema:
116
+ * type: string
117
+ * description: Playlist ID
118
+ * - in: query
119
+ * name: radio
120
+ * schema:
121
+ * type: boolean
122
+ * default: false
123
+ * description: Radio mode
124
+ * - in: query
125
+ * name: shuffle
126
+ * schema:
127
+ * type: boolean
128
+ * default: false
129
+ * description: Shuffle mode
130
+ * - in: query
131
+ * name: limit
132
+ * schema:
133
+ * type: integer
134
+ * default: 25
135
+ * description: Maximum number of tracks
136
+ * responses:
137
+ * 200:
138
+ * description: Watch playlist data
139
+ * 400:
140
+ * description: Missing params
141
+ */
142
+ router.get('/watch_playlist', async (req, res) => {
143
+ try {
144
+ const { videoId, playlistId, radio = false, shuffle = false, limit = 25 } = req.query;
145
+
146
+ if (!videoId && !playlistId) {
147
+ return res.status(400).json({ error: 'Provide either videoId or playlistId' });
148
+ }
149
+
150
+ const ytmusic = req.app.locals.ytmusic;
151
+ const data = await ytmusic.getWatchPlaylist(
152
+ videoId,
153
+ playlistId,
154
+ radio === 'true',
155
+ shuffle === 'true',
156
+ parseInt(limit)
157
+ );
158
+
159
+ res.json(data);
160
+ } catch (error) {
161
+ console.error('Watch playlist error:', error);
162
+ res.status(500).json({ error: `Watch playlist unavailable: ${error.message}` });
163
+ }
164
+ });
165
+
166
+ module.exports = router;
routes/jiosaavn.js ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const JioSaavn = require('../lib/jiosaavn');
3
+ const router = express.Router();
4
+
5
+ const jiosaavn = new JioSaavn();
6
+
7
+ /**
8
+ * @swagger
9
+ * /api/jiosaavn/search:
10
+ * get:
11
+ * summary: Search for music on JioSaavn
12
+ * parameters:
13
+ * - in: query
14
+ * name: title
15
+ * required: true
16
+ * schema:
17
+ * type: string
18
+ * description: Song title
19
+ * - in: query
20
+ * name: artist
21
+ * required: true
22
+ * schema:
23
+ * type: string
24
+ * description: Artist name
25
+ * - in: query
26
+ * name: debug
27
+ * schema:
28
+ * type: integer
29
+ * enum: [0, 1]
30
+ * default: 0
31
+ * description: Enable debug mode
32
+ * responses:
33
+ * 200:
34
+ * description: Song information with download URL
35
+ * 400:
36
+ * description: Missing title or artist parameters
37
+ * 404:
38
+ * description: Music stream not found
39
+ * 500:
40
+ * description: Internal server error
41
+ */
42
+ router.get('/jiosaavn/search', async (req, res) => {
43
+ try {
44
+ const { title, artist, debug = 0 } = req.query;
45
+
46
+ if (!title || !artist) {
47
+ return res.status(400).json({ error: 'Missing title or artist parameters' });
48
+ }
49
+
50
+ const debugMode = debug === '1';
51
+ const result = await jiosaavn.search(title, artist, debugMode);
52
+
53
+ res.json(result);
54
+ } catch (error) {
55
+ console.error('JioSaavn search error:', error);
56
+ res.status(500).json({ error: `JioSaavn search failed: ${error.message}` });
57
+ }
58
+ });
59
+
60
+ /**
61
+ * @swagger
62
+ * /api/jiosaavn/search/all:
63
+ * get:
64
+ * summary: Search for all music results on JioSaavn
65
+ * parameters:
66
+ * - in: query
67
+ * name: q
68
+ * required: true
69
+ * schema:
70
+ * type: string
71
+ * description: Search query
72
+ * - in: query
73
+ * name: limit
74
+ * schema:
75
+ * type: integer
76
+ * default: 10
77
+ * description: Number of results to return
78
+ * - in: query
79
+ * name: debug
80
+ * schema:
81
+ * type: integer
82
+ * enum: [0, 1]
83
+ * default: 0
84
+ * description: Enable debug mode
85
+ * responses:
86
+ * 200:
87
+ * description: List of all matching songs
88
+ * 400:
89
+ * description: Missing query parameter
90
+ * 500:
91
+ * description: Internal server error
92
+ */
93
+ router.get('/jiosaavn/search/all', async (req, res) => {
94
+ try {
95
+ const { q: query, limit = 10, debug = 0 } = req.query;
96
+
97
+ if (!query) {
98
+ return res.status(400).json({ error: "Missing query parameter 'q'" });
99
+ }
100
+
101
+ const debugMode = debug === '1';
102
+ const result = await jiosaavn.searchAll(query, parseInt(limit), debugMode);
103
+
104
+ res.json(result);
105
+ } catch (error) {
106
+ console.error('JioSaavn search all error:', error);
107
+ res.status(500).json({ error: `JioSaavn search all failed: ${error.message}` });
108
+ }
109
+ });
110
+
111
+ module.exports = router;
routes/youtube.js ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+
3
+ const router = express.Router();
4
+
5
+ const YT_FILTERS = new Set(['all', 'channels', 'playlists', 'videos']);
6
+
7
+ /**
8
+ * @swagger
9
+ * /api/yt_search:
10
+ * get:
11
+ * summary: Search YouTube
12
+ * parameters:
13
+ * - in: query
14
+ * name: q
15
+ * required: true
16
+ * schema:
17
+ * type: string
18
+ * description: Search query string
19
+ * - in: query
20
+ * name: filter
21
+ * schema:
22
+ * type: string
23
+ * enum: [all, channels, playlists, videos]
24
+ * default: all
25
+ * description: Filter results by type
26
+ * - in: query
27
+ * name: continuationToken
28
+ * schema:
29
+ * type: string
30
+ * description: Continuation token for pagination
31
+ * responses:
32
+ * 200:
33
+ * description: YouTube search results with continuation token
34
+ * 400:
35
+ * description: Missing/invalid params
36
+ */
37
+ router.get('/yt_search', async (req, res) => {
38
+ try {
39
+ const { q: query, filter = 'all', continuationToken } = req.query;
40
+
41
+ // FIXED: Allow continuation without query
42
+ if (!query && !continuationToken) {
43
+ return res.status(400).json({ error: "Missing required query parameter 'q' or 'continuationToken'" });
44
+ }
45
+
46
+ if (!YT_FILTERS.has(filter)) {
47
+ return res.status(400).json({
48
+ error: `Invalid filter. Allowed: ${Array.from(YT_FILTERS).sort()}`
49
+ });
50
+ }
51
+
52
+ const youtubeSearch = req.app.locals.youtubeSearch;
53
+ let results = [];
54
+ let nextContinuationToken = null;
55
+
56
+ // When continuation token is provided, only search the specific filter type
57
+ if (continuationToken) {
58
+ // FIXED: Don't pass query when using continuation token
59
+ if (filter === 'videos') {
60
+ const videoResults = await youtubeSearch.searchVideos(null, continuationToken);
61
+ results = videoResults.results;
62
+ nextContinuationToken = videoResults.continuationToken;
63
+ } else if (filter === 'channels') {
64
+ const channelResults = await youtubeSearch.searchChannels(null, continuationToken);
65
+ results = channelResults.results;
66
+ nextContinuationToken = channelResults.continuationToken;
67
+ } else if (filter === 'playlists') {
68
+ const playlistResults = await youtubeSearch.searchPlaylists(null, continuationToken);
69
+ results = playlistResults.results;
70
+ nextContinuationToken = playlistResults.continuationToken;
71
+ }
72
+ } else {
73
+ // Initial search without continuation token
74
+ if (filter === 'videos' || filter === 'all') {
75
+ const videoResults = await youtubeSearch.searchVideos(query, null);
76
+ results.push(...videoResults.results);
77
+ nextContinuationToken = videoResults.continuationToken;
78
+ }
79
+
80
+ if (filter === 'channels' || filter === 'all') {
81
+ const channelResults = await youtubeSearch.searchChannels(query, null);
82
+ results.push(...channelResults.results);
83
+ if (!nextContinuationToken) nextContinuationToken = channelResults.continuationToken;
84
+ }
85
+
86
+ if (filter === 'playlists' || filter === 'all') {
87
+ const playlistResults = await youtubeSearch.searchPlaylists(query, null);
88
+ results.push(...playlistResults.results);
89
+ if (!nextContinuationToken) nextContinuationToken = playlistResults.continuationToken;
90
+ }
91
+ }
92
+
93
+ // Include continuationToken at the end
94
+ res.json({
95
+ filter,
96
+ query: query || null,
97
+ results,
98
+ continuationToken: nextContinuationToken
99
+ });
100
+ } catch (error) {
101
+ console.error('YouTube search error:', error);
102
+ res.status(500).json({ error: `Search failed: ${error.message}` });
103
+ }
104
+ });
105
+
106
+ /**
107
+ * @swagger
108
+ * /api/yt_channel/{channelId}:
109
+ * get:
110
+ * summary: Get YouTube channel information
111
+ * parameters:
112
+ * - in: path
113
+ * name: channelId
114
+ * required: true
115
+ * schema:
116
+ * type: string
117
+ * description: YouTube channel ID
118
+ * responses:
119
+ * 200:
120
+ * description: Channel information
121
+ * 400:
122
+ * description: Invalid channel ID
123
+ */
124
+ router.get('/yt_channel/:channelId', async (req, res) => {
125
+ try {
126
+ const { channelId } = req.params;
127
+ const youtubeSearch = req.app.locals.youtubeSearch;
128
+
129
+ // Get channel info using search
130
+ const channelResults = await youtubeSearch.searchChannels(`channel:${channelId}`, null);
131
+
132
+ if (channelResults.results.length === 0) {
133
+ return res.status(404).json({ error: 'Channel not found' });
134
+ }
135
+
136
+ res.json({
137
+ channelId,
138
+ channelInfo: channelResults.results[0]
139
+ });
140
+ } catch (error) {
141
+ console.error('YouTube channel error:', error);
142
+ res.status(500).json({ error: `Failed to get channel info: ${error.message}` });
143
+ }
144
+ });
145
+
146
+ /**
147
+ * @swagger
148
+ * /api/yt_playlists:
149
+ * get:
150
+ * summary: Search YouTube playlists
151
+ * parameters:
152
+ * - in: query
153
+ * name: q
154
+ * required: true
155
+ * schema:
156
+ * type: string
157
+ * description: Search query for playlists
158
+ * - in: query
159
+ * name: continuationToken
160
+ * schema:
161
+ * type: string
162
+ * description: Continuation token for pagination
163
+ * responses:
164
+ * 200:
165
+ * description: YouTube playlists with continuation token
166
+ * 400:
167
+ * description: Missing/invalid params
168
+ */
169
+ router.get('/yt_playlists', async (req, res) => {
170
+ try {
171
+ const { q: query, continuationToken } = req.query;
172
+
173
+ // FIXED: Allow continuation without query
174
+ if (!query && !continuationToken) {
175
+ return res.status(400).json({ error: "Missing required query parameter 'q' or 'continuationToken'" });
176
+ }
177
+
178
+ const youtubeSearch = req.app.locals.youtubeSearch;
179
+ const playlistResults = await youtubeSearch.searchPlaylists(
180
+ query || null,
181
+ continuationToken
182
+ );
183
+
184
+ res.json({
185
+ query: query || null,
186
+ playlists: playlistResults.results,
187
+ continuationToken: playlistResults.continuationToken
188
+ });
189
+ } catch (error) {
190
+ console.error('YouTube playlists error:', error);
191
+ res.status(500).json({ error: `Failed to search playlists: ${error.message}` });
192
+ }
193
+ });
194
+
195
+ module.exports = router;
test.html ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Music API - Endpoint Tester</title>
7
+ <style>
8
+ body { font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Helvetica Neue, Arial; margin: 24px; }
9
+ h1 { margin: 0 0 4px; }
10
+ .subtitle { color: #666; margin: 0 0 16px; }
11
+ .card { border: 1px solid #ddd; border-radius: 10px; padding: 16px; margin-bottom: 16px; }
12
+ .row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
13
+ .row > * { margin: 4px 0; }
14
+ label { font-size: 12px; color: #333; }
15
+ input, select, button, textarea { font-size: 14px; padding: 8px 10px; }
16
+ input, select, textarea { border: 1px solid #ccc; border-radius: 8px; }
17
+ button { border: 1px solid #333; background: #111; color: #fff; border-radius: 8px; cursor: pointer; }
18
+ button.secondary { background: #fff; color: #111; }
19
+ code.url { display: block; background: #f7f7f7; padding: 8px; border-radius: 8px; overflow: auto; }
20
+ pre { background: #0b1020; color: #d7e8ff; padding: 12px; border-radius: 10px; overflow: auto; }
21
+ .two { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
22
+ @media (max-width: 900px) { .two { grid-template-columns: 1fr; } }
23
+ </style>
24
+ <script>
25
+ const base = 'http://localhost:5000';
26
+
27
+ function $(id) { return document.getElementById(id); }
28
+ function setJSON(id, value) { $(id).textContent = JSON.stringify(value, null, 2); }
29
+ function setText(id, value) { $(id).textContent = value || ''; }
30
+
31
+ function buildUrl(path, params) {
32
+ const url = new URL(path, base);
33
+ Object.entries(params || {}).forEach(([k, v]) => {
34
+ if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, v);
35
+ });
36
+ return url.toString();
37
+ }
38
+
39
+ async function doFetch({ path, params, outUrlId, outJsonId, onAfter }) {
40
+ const url = buildUrl(path, params);
41
+ setText(outUrlId, url);
42
+ try {
43
+ const res = await fetch(url);
44
+ const json = await res.json();
45
+ setJSON(outJsonId, json);
46
+ if (typeof onAfter === 'function') onAfter(json);
47
+ } catch (e) {
48
+ setJSON(outJsonId, { error: e.message });
49
+ }
50
+ }
51
+
52
+ // Shared continuation helpers
53
+ function applyContinuation(fromJson, toInputIdList = []) {
54
+ const token = fromJson?.continuationToken
55
+ || fromJson?.results?.continuationToken
56
+ || null;
57
+ toInputIdList.forEach(id => { $(id).value = token || ''; });
58
+ return token;
59
+ }
60
+
61
+ // Handlers
62
+ async function ytmSearch(initial = true) {
63
+ const q = $('ytm_q').value.trim();
64
+ const filter = $('ytm_filter').value;
65
+ const continuationToken = initial ? '' : $('ytm_ct').value.trim();
66
+ await doFetch({
67
+ path: '/api/search',
68
+ params: { q, filter, continuationToken },
69
+ outUrlId: 'ytm_url',
70
+ outJsonId: 'ytm_json',
71
+ onAfter: (json) => {
72
+ // autofill continuation
73
+ applyContinuation(json, ['ytm_ct']);
74
+ }
75
+ });
76
+ }
77
+
78
+ async function ytSearch(initial = true) {
79
+ const q = $('yt_q').value.trim();
80
+ const filter = $('yt_filter').value;
81
+ const continuationToken = initial ? '' : $('yt_ct').value.trim();
82
+ await doFetch({
83
+ path: '/api/yt_search',
84
+ params: { q, filter, continuationToken },
85
+ outUrlId: 'yt_url',
86
+ outJsonId: 'yt_json',
87
+ onAfter: (json) => {
88
+ applyContinuation(json, ['yt_ct']);
89
+ }
90
+ });
91
+ }
92
+
93
+ async function ytPlaylists(initial = true) {
94
+ const q = $('ytp_q').value.trim();
95
+ const continuationToken = initial ? '' : $('ytp_ct').value.trim();
96
+ await doFetch({
97
+ path: '/api/yt_playlists',
98
+ params: { q, continuationToken },
99
+ outUrlId: 'ytp_url',
100
+ outJsonId: 'ytp_json',
101
+ onAfter: (json) => {
102
+ applyContinuation(json, ['ytp_ct']);
103
+ }
104
+ });
105
+ }
106
+
107
+ // Quick presets
108
+ function presetPhonk() {
109
+ ['ytm_q','yt_q','ytp_q'].forEach(id => { $(id).value = 'phonk'; });
110
+ }
111
+ window.addEventListener('DOMContentLoaded', presetPhonk);
112
+ </script>
113
+ </head>
114
+ <body>
115
+ <h1>Music API - Endpoint Tester</h1>
116
+ <p class="subtitle">Run requests against the local API, inspect JSON, and page with continuation tokens.</p>
117
+
118
+ <div class="card">
119
+ <h2>YouTube Music: /api/search</h2>
120
+ <div class="row">
121
+ <label>Query <input id="ytm_q" placeholder="e.g. phonk"></label>
122
+ <label>Filter
123
+ <select id="ytm_filter">
124
+ <option value="songs">songs</option>
125
+ <option value="videos">videos</option>
126
+ <option value="albums">albums</option>
127
+ <option value="artists">artists</option>
128
+ <option value="playlists">playlists</option>
129
+ <option value="community_playlists">community_playlists</option>
130
+ <option value="profiles">profiles</option>
131
+ <option value="podcasts">podcasts</option>
132
+ <option value="episodes">episodes</option>
133
+ </select>
134
+ </label>
135
+ <label>Continuation <input id="ytm_ct" placeholder="continuationToken"></label>
136
+ <button onclick="ytmSearch(true)">Search</button>
137
+ <button class="secondary" onclick="ytmSearch(false)">Next page ▶</button>
138
+ </div>
139
+ <code class="url" id="ytm_url"></code>
140
+ <pre id="ytm_json">{}</pre>
141
+ </div>
142
+
143
+ <div class="card">
144
+ <h2>YouTube: /api/yt_search</h2>
145
+ <div class="row">
146
+ <label>Query <input id="yt_q" placeholder="e.g. phonk"></label>
147
+ <label>Filter
148
+ <select id="yt_filter">
149
+ <option value="videos">videos</option>
150
+ <option value="all">all</option>
151
+ <option value="channels">channels</option>
152
+ <option value="playlists">playlists</option>
153
+ </select>
154
+ </label>
155
+ <label>Continuation <input id="yt_ct" placeholder="continuationToken"></label>
156
+ <button onclick="ytSearch(true)">Search</button>
157
+ <button class="secondary" onclick="ytSearch(false)">Next page ▶</button>
158
+ </div>
159
+ <code class="url" id="yt_url"></code>
160
+ <pre id="yt_json">{}</pre>
161
+ </div>
162
+
163
+ <div class="card">
164
+ <h2>YouTube: /api/yt_playlists</h2>
165
+ <div class="row">
166
+ <label>Query <input id="ytp_q" placeholder="e.g. phonk"></label>
167
+ <label>Continuation <input id="ytp_ct" placeholder="continuationToken"></label>
168
+ <button onclick="ytPlaylists(true)">Search</button>
169
+ <button class="secondary" onclick="ytPlaylists(false)">Next page ▶</button>
170
+ </div>
171
+ <code class="url" id="ytp_url"></code>
172
+ <pre id="ytp_json">{}</pre>
173
+ </div>
174
+
175
+ <div class="card">
176
+ <h2>Notes</h2>
177
+ <ul>
178
+ <li>Continuation tokens are auto-populated into the input after a response. Click "Next page" to fetch the next page.</li>
179
+ <li>This page targets the API served by the current origin (location.origin).</li>
180
+ <li>Open DevTools (Network tab) if you need to inspect raw requests.</li>
181
+ </ul>
182
+ </div>
183
+ </body>
184
+ </html>
185
+
186
+