File size: 5,286 Bytes
226daaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import puppeteer from 'puppeteer-core';
import fs from 'fs';
import path from 'path';

let cachedCreds = null;
let credsExpiresAt = 0;

const parseNetscapeCookies = (text) => {
  const cookies = [];
  for (const line of text.split('\n')) {
    if (!line.trim() || line.startsWith('#')) continue;
    const parts = line.split('\t');
    if (parts.length >= 7) {
      cookies.push({
        name: parts[5],
        value: parts[6].trim(),
        domain: parts[0],
        path: parts[2],
        secure: parts[3] === 'TRUE',
        expires: parseFloat(parts[4])
      });
    }
  }
  return cookies;
};

const getExecutablePath = () => {
  if (process.env.PUPPETEER_EXECUTABLE_PATH) {
    return process.env.PUPPETEER_EXECUTABLE_PATH;
  }
  if (process.platform === 'darwin') {
    return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
  }
  for (const p of ['/usr/bin/chromium-browser', '/usr/bin/google-chrome', '/usr/bin/chromium']) {
    if (fs.existsSync(p)) return p;
  }
  return null;
};

export const getBrowserCredentials = async () => {
  if (cachedCreds && Date.now() < credsExpiresAt) {
    return cachedCreds;
  }

  const cookiePath = path.resolve('cookies.txt');
  if (!fs.existsSync(cookiePath)) {
    throw new Error('cookies.txt not found in project root.');
  }

  const executablePath = getExecutablePath();
  if (!executablePath) {
    throw new Error('Chrome/Chromium not found. Install Chrome or set PUPPETEER_EXECUTABLE_PATH.');
  }

  console.log('Launching headless browser to retrieve Spotify credentials...');
  const cookieText = fs.readFileSync(cookiePath, 'utf8');
  const cookies = parseNetscapeCookies(cookieText);

  const browser = await puppeteer.launch({
    executablePath,
    headless: true,
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu']
  });

  try {
    const page = await browser.newPage();
    await page.setCookie(...cookies);

    let authorization = null;
    let clientToken = null;

    const credsPromise = new Promise((resolve) => {
      page.on('request', request => {
        const headers = request.headers();
        if (headers['authorization'] && headers['authorization'].startsWith('Bearer ') && headers['client-token']) {
          if (!authorization) {
            authorization = headers['authorization'].split(' ')[1];
            clientToken = headers['client-token'];
            resolve({ authorization, clientToken });
          }
        }
      });
    });

    await page.goto('https://open.spotify.com/search', { waitUntil: 'networkidle2', timeout: 30000 });

    const creds = await Promise.race([
      credsPromise,
      new Promise((_, reject) => setTimeout(() => reject(new Error('Credential detection timed out')), 15000))
    ]);

    // Cache for 50 minutes
    cachedCreds = creds;
    credsExpiresAt = Date.now() + 50 * 60 * 1000;
    console.log('Credentials retrieved and cached successfully.');
    return creds;
  } finally {
    await browser.close();
  }
};

// Search using Spotify's internal GraphQL v2 endpoint
export const searchSpotifyGraphQL = async (query, limit = 20) => {
  const { authorization, clientToken } = await getBrowserCredentials();

  const payload = {
    variables: {
      query,
      limit,
      offset: 0,
      numberOfTopResults: limit,
      includeArtistHasConcertsField: false,
      includeAudiobooks: false,
      includeAuthors: false,
      includePreReleases: true,
      includeAlbumPreReleases: true,
      includeEpisodeContentRatingsV2: false,
      isPrefix: null
    },
    operationName: 'searchTopResultsList',
    extensions: {
      persistedQuery: {
        version: 1,
        sha256Hash: '63a93cc04f6d8dea84a85de315e43f396a76cb681500de9ac5ccf5fc618c84cb'
      }
    }
  };

  const axios = (await import('axios')).default;
  const response = await axios.post('https://api-partner.spotify.com/pathfinder/v2/query', payload, {
    headers: {
      'accept': 'application/json',
      'content-type': 'application/json;charset=UTF-8',
      'authorization': `Bearer ${authorization}`,
      'client-token': clientToken,
      'app-platform': 'WebPlayer',
      'origin': 'https://open.spotify.com',
      'referer': 'https://open.spotify.com/',
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36',
      'spotify-app-version': '1.2.95.15.g813d8ea0'
    }
  });

  // Extract tracks from the GraphQL response
  const topResults = response.data?.data?.searchV2?.topResultsV2?.itemsV2 || [];
  const tracks = topResults
    .filter(item => item?.item?.__typename === 'TrackResponseWrapper')
    .map(item => {
      const d = item.item.data;
      return {
        id: d.id,
        name: d.name,
        uri: d.uri,
        artists: (d.artists?.items || []).map(a => ({ name: a.profile.name, uri: a.uri })),
        duration_ms: d.duration?.totalMilliseconds,
        album: {
          name: d.albumOfTrack?.name,
          id: d.albumOfTrack?.id
        }
      };
    });

  return tracks;
};

// Backwards compatible export for token-only consumers
export const getBrowserSearchToken = async () => {
  const { authorization } = await getBrowserCredentials();
  return authorization;
};