veltrixcode commited on
Commit
8672672
·
verified ·
1 Parent(s): 3c4e2de

Upload 12 files

Browse files
README.md CHANGED
@@ -1,11 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
- title: Jsondb
3
- emoji: 🏆
4
- colorFrom: red
5
- colorTo: blue
6
- sdk: docker
7
- pinned: false
8
- license: mit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  ---
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Spotify Canvas API
2
+
3
+ Unofficial API to fetch Spotify **Canvas video data** (the looping visual videos that appear behind songs on mobile).
4
+
5
+ > [!WARNING]
6
+ > This project uses undocumented endpoints and may violate [Spotify's Terms of Service](https://www.spotify.com/legal/end-user-agreement/). Use at your own risk.
7
+
8
+ ---
9
+
10
+ ## Features
11
+
12
+ - Retrieve **Canvas video URLs** by track ID or URI
13
+ - Parses Protobuf responses from the internal Spotify API
14
+ - Works with public or private tracks (as long as you're authenticated)
15
+
16
  ---
17
+
18
+ ## Example Request
19
+
20
+ ### GET `/api/canvas`
21
+
22
+ ```bash
23
+ https://localhost:3000/api/canvas?trackId=3OHfY25tqY28d16oZczHc8
24
+ ```
25
+
26
+ ### Response:
27
+ ```json
28
+ {
29
+ "data": {
30
+ "canvasesList": [
31
+ {
32
+ "id": "32b57cbf354b453a95eee32bb04d4e42",
33
+ "canvasUrl": "https://canvaz.scdn.co/upload/licensor/5bSw7fRotCnRCcO9br14W5/video/32b57cbf354b453a95eee32bb04d4e42.cnvs.mp4",
34
+ "trackUri": "spotify:track:3OHfY25tqY28d16oZczHc8",
35
+ "artist": {
36
+ "artistUri": "spotify:artist:7tYKF4w9nC0nq9CsPZTHyP",
37
+ "artistName": "SZA",
38
+ "artistImgUrl": "https://i.scdn.co/image/ab6761610000f1780895066d172e1f51f520bc65"
39
+ },
40
+ "otherId": "2c441fceb502eaa25f26bcd5b1ccfc0d",
41
+ "canvasUri": "spotify:canvas:1xGyujDyxbx4eTPD4nKLw6"
42
+ }
43
+ ]
44
+ }
45
+ }
46
+ ```
47
+
48
  ---
49
 
50
+ ## Setup
51
+
52
+ ### 1. Clone the Repo
53
+
54
+ ```bash
55
+ git clone https://github.com/Paxsenix0/Spotify-Canvas-API.git
56
+ cd Spotify-Canvas-API
57
+ ```
58
+
59
+ ### 2. Install Dependencies
60
+
61
+ ```bash
62
+ npm install
63
+ ```
64
+
65
+ ### 3. Set Required Environment Variable
66
+
67
+ You must supply your sp_dc cookie from a logged-in Spotify session.
68
+
69
+ Create a .env file in the root:
70
+
71
+ ```bash
72
+ SP_DC=your_sp_dc_cookie_here
73
+ ```
74
+
75
+ > This cookie is used to generate an access token to authenticate requests.
76
+
77
+ ---
78
+
79
+ ## Deployment
80
+
81
+ You can deploy instantly with Vercel:
82
+
83
+ [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FPaxsenix0%2FSpotify-Canvas-API%2Ftree%2Fmain&project-name=Spotify-Canvas-API&repository-name=Spotify-Canvas-API&env=SP_DC&envDescription=SP_DC%20is%20needed%20for%20this%20for%20authentication%20to%20be%20working%20fine&envLink=https%3A%2F%2Fwww.spotify.com%2F&redirect-url=https%3A%2F%2Fgithub.com%2FPaxsenix0%2FSpotify-Canvas-API)
84
+
85
+ ---
86
+
87
+ ## Notes
88
+
89
+ > I'm developing this project entirely on my phone, without a PC or laptop. Also, I'm still learning — so feel free to send pull requests or suggestions if something looks off!
90
+
91
+ ---
92
+
93
+ ## Reference
94
+
95
+ Shoutout to this helpful repo that inspired parts of this:
96
+ https://github.com/bartleyg/my-spotify-canvas
97
+
98
+ ---
99
+
100
+ ## License
101
+
102
+ This project is licensed under the MIT license. see [LICENSE](https://github.com/Paxsenix0/Spotify-Canvas-API/blob/initial/LICENSE) for details.
103
+
104
+ ---
105
+
106
+ ## Contact
107
+
108
+ Telegram: [@paxsenix0](https://t.me/paxsenix0)
109
+
110
+ Email: alex24dzn@proton.me
111
+
112
+ My Rest-API website: https://api.paxsenix.biz.id
113
+
114
+ ---
index.js CHANGED
@@ -1,15 +1,19 @@
1
  import express from 'express';
2
- import axios from 'axios';
3
  import canvasRoutes from './routes/canvasRoutes.js';
4
- import dotenv from 'dotenv';
5
 
6
- dotenv.config();
7
  const app = express();
8
  const PORT = process.env.PORT || 7860;
9
 
10
  app.use('/api/canvas', canvasRoutes);
11
 
12
- app.listen(PORT, function () {
13
  console.log("Listening on PORT: ", PORT);
14
  console.log(`Running on local: http://localhost:${PORT}`);
 
 
 
 
 
 
15
  });
 
1
  import express from 'express';
 
2
  import canvasRoutes from './routes/canvasRoutes.js';
3
+ import { initPersistentBrowser } from './services/browserAuthService.js';
4
 
 
5
  const app = express();
6
  const PORT = process.env.PORT || 7860;
7
 
8
  app.use('/api/canvas', canvasRoutes);
9
 
10
+ app.listen(PORT, async function () {
11
  console.log("Listening on PORT: ", PORT);
12
  console.log(`Running on local: http://localhost:${PORT}`);
13
+ try {
14
+ await initPersistentBrowser();
15
+ console.log('Persistent browser initialized successfully.');
16
+ } catch (err) {
17
+ console.error('Failed to initialize persistent browser:', err.message);
18
+ }
19
  });
package-lock.json CHANGED
@@ -10,7 +10,6 @@
10
  "license": "MIT",
11
  "dependencies": {
12
  "axios": "^1.6.0",
13
- "dotenv": "latest",
14
  "express": "latest",
15
  "google-protobuf": "^3.11.4",
16
  "otpauth": "latest",
@@ -322,18 +321,6 @@
322
  "integrity": "sha512-mXwg4Fqnv0WR4iuAT/gYUmctNkjILwXFHyZ+m7Ty1dfr0ezZt2U3gnrrJTfRobJTHoXf+IbuFvFITzLrLFjwJA==",
323
  "license": "BSD-3-Clause"
324
  },
325
- "node_modules/dotenv": {
326
- "version": "17.4.2",
327
- "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
328
- "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
329
- "license": "BSD-2-Clause",
330
- "engines": {
331
- "node": ">=12"
332
- },
333
- "funding": {
334
- "url": "https://dotenvx.com"
335
- }
336
- },
337
  "node_modules/dunder-proto": {
338
  "version": "1.0.1",
339
  "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
 
10
  "license": "MIT",
11
  "dependencies": {
12
  "axios": "^1.6.0",
 
13
  "express": "latest",
14
  "google-protobuf": "^3.11.4",
15
  "otpauth": "latest",
 
321
  "integrity": "sha512-mXwg4Fqnv0WR4iuAT/gYUmctNkjILwXFHyZ+m7Ty1dfr0ezZt2U3gnrrJTfRobJTHoXf+IbuFvFITzLrLFjwJA==",
322
  "license": "BSD-3-Clause"
323
  },
 
 
 
 
 
 
 
 
 
 
 
 
324
  "node_modules/dunder-proto": {
325
  "version": "1.0.1",
326
  "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
package.json CHANGED
@@ -13,7 +13,6 @@
13
  "license": "MIT",
14
  "dependencies": {
15
  "axios": "^1.6.0",
16
- "dotenv": "latest",
17
  "express": "latest",
18
  "google-protobuf": "^3.11.4",
19
  "otpauth": "latest",
 
13
  "license": "MIT",
14
  "dependencies": {
15
  "axios": "^1.6.0",
 
16
  "express": "latest",
17
  "google-protobuf": "^3.11.4",
18
  "otpauth": "latest",
services/browserAuthService.js CHANGED
@@ -1,9 +1,13 @@
1
  import puppeteer from 'puppeteer-core';
2
  import fs from 'fs';
3
  import path from 'path';
 
4
 
5
  let cachedCreds = null;
6
  let credsExpiresAt = 0;
 
 
 
7
 
8
  const parseNetscapeCookies = (text) => {
9
  const cookies = [];
@@ -37,9 +41,26 @@ const getExecutablePath = () => {
37
  return null;
38
  };
39
 
40
- export const getBrowserCredentials = async () => {
41
- if (cachedCreds && Date.now() < credsExpiresAt) {
42
- return cachedCreds;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  }
44
 
45
  const cookiePath = path.resolve('cookies.txt');
@@ -52,50 +73,80 @@ export const getBrowserCredentials = async () => {
52
  throw new Error('Chrome/Chromium not found. Install Chrome or set PUPPETEER_EXECUTABLE_PATH.');
53
  }
54
 
55
- console.log('Launching headless browser to retrieve Spotify credentials...');
56
  const cookieText = fs.readFileSync(cookiePath, 'utf8');
57
  const cookies = parseNetscapeCookies(cookieText);
58
 
59
- const browser = await puppeteer.launch({
60
  executablePath,
61
  headless: true,
62
  args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu']
63
  });
64
 
65
- try {
66
- const page = await browser.newPage();
67
- await page.setCookie(...cookies);
68
-
69
- let authorization = null;
70
- let clientToken = null;
71
-
72
- const credsPromise = new Promise((resolve) => {
73
- page.on('request', request => {
74
- const headers = request.headers();
75
- if (headers['authorization'] && headers['authorization'].startsWith('Bearer ') && headers['client-token']) {
76
- if (!authorization) {
77
- authorization = headers['authorization'].split(' ')[1];
78
- clientToken = headers['client-token'];
79
- resolve({ authorization, clientToken });
80
- }
81
- }
82
- });
83
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
- await page.goto('https://open.spotify.com/search', { waitUntil: 'networkidle2', timeout: 30000 });
 
 
86
 
 
 
 
 
 
 
 
 
87
  const creds = await Promise.race([
88
  credsPromise,
89
- new Promise((_, reject) => setTimeout(() => reject(new Error('Credential detection timed out')), 15000))
90
  ]);
91
-
92
- // Cache for 50 minutes
93
- cachedCreds = creds;
94
- credsExpiresAt = Date.now() + 50 * 60 * 1000;
95
- console.log('Credentials retrieved and cached successfully.');
96
  return creds;
97
- } finally {
98
- await browser.close();
 
99
  }
100
  };
101
 
 
1
  import puppeteer from 'puppeteer-core';
2
  import fs from 'fs';
3
  import path from 'path';
4
+ import { updateSpDc } from './spotifyAuthService.js';
5
 
6
  let cachedCreds = null;
7
  let credsExpiresAt = 0;
8
+ let browser = null;
9
+ let page = null;
10
+ let pendingCredsResolver = null;
11
 
12
  const parseNetscapeCookies = (text) => {
13
  const cookies = [];
 
41
  return null;
42
  };
43
 
44
+ // Update cookies from browser context to sp_dc
45
+ const syncCookies = async () => {
46
+ if (!page) return;
47
+ try {
48
+ const pageCookies = await page.cookies();
49
+ const spDcCookie = pageCookies.find(c => c.name === 'sp_dc');
50
+ if (spDcCookie) {
51
+ updateSpDc(spDcCookie.value);
52
+ console.log('Synced sp_dc cookie from persistent browser:', spDcCookie.value);
53
+ }
54
+ } catch (error) {
55
+ console.error('Failed to sync cookies from browser:', error.message);
56
+ }
57
+ };
58
+
59
+ export const initPersistentBrowser = async () => {
60
+ if (browser) {
61
+ try {
62
+ await browser.close();
63
+ } catch (e) {}
64
  }
65
 
66
  const cookiePath = path.resolve('cookies.txt');
 
73
  throw new Error('Chrome/Chromium not found. Install Chrome or set PUPPETEER_EXECUTABLE_PATH.');
74
  }
75
 
76
+ console.log('Starting persistent headless browser...');
77
  const cookieText = fs.readFileSync(cookiePath, 'utf8');
78
  const cookies = parseNetscapeCookies(cookieText);
79
 
80
+ browser = await puppeteer.launch({
81
  executablePath,
82
  headless: true,
83
  args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu']
84
  });
85
 
86
+ page = await browser.newPage();
87
+ await page.setCookie(...cookies);
88
+
89
+ page.on('request', async (request) => {
90
+ const headers = request.headers();
91
+ if (headers['authorization'] && headers['authorization'].startsWith('Bearer ') && headers['client-token']) {
92
+ const authorization = headers['authorization'].split(' ')[1];
93
+ const clientToken = headers['client-token'];
94
+
95
+ cachedCreds = { authorization, clientToken };
96
+ // Cache for 50 minutes
97
+ credsExpiresAt = Date.now() + 50 * 60 * 1000;
98
+
99
+ if (pendingCredsResolver) {
100
+ pendingCredsResolver(cachedCreds);
101
+ pendingCredsResolver = null;
102
+ }
103
+ }
104
+ });
105
+
106
+ // Periodically sync sp_dc cookie and reload page to keep session alive
107
+ page.on('load', syncCookies);
108
+
109
+ console.log('Navigating persistent browser to Spotify...');
110
+ await page.goto('https://open.spotify.com/search', { waitUntil: 'networkidle2', timeout: 60000 });
111
+ await syncCookies();
112
+
113
+ // Refresh every 15 minutes to prevent session expiration/idle timeout
114
+ setInterval(async () => {
115
+ try {
116
+ console.log('Refreshing persistent browser page to keep session active...');
117
+ await page.reload({ waitUntil: 'networkidle2', timeout: 30000 });
118
+ await syncCookies();
119
+ } catch (error) {
120
+ console.error('Error refreshing persistent browser page:', error.message);
121
+ }
122
+ }, 15 * 60 * 1000);
123
+ };
124
+
125
+ export const getBrowserCredentials = async () => {
126
+ if (!browser || !page) {
127
+ await initPersistentBrowser();
128
+ }
129
 
130
+ if (cachedCreds && Date.now() < credsExpiresAt) {
131
+ return cachedCreds;
132
+ }
133
 
134
+ console.log('Credentials expired or missing, refreshing page to retrieve new Spotify credentials...');
135
+
136
+ const credsPromise = new Promise((resolve) => {
137
+ pendingCredsResolver = resolve;
138
+ });
139
+
140
+ try {
141
+ await page.reload({ waitUntil: 'networkidle2', timeout: 30000 });
142
  const creds = await Promise.race([
143
  credsPromise,
144
+ new Promise((_, reject) => setTimeout(() => reject(new Error('Credential detection timed out')), 20000))
145
  ]);
 
 
 
 
 
146
  return creds;
147
+ } catch (error) {
148
+ pendingCredsResolver = null;
149
+ throw error;
150
  }
151
  };
152
 
services/spotifyAuthService.js CHANGED
@@ -1,23 +1,17 @@
1
  import axios from "axios";
2
  import * as OTPAuth from "otpauth";
3
- import dotenv from "dotenv";
4
  import fs from "fs";
5
  import { fileURLToPath } from "url";
6
 
7
- dotenv.config();
8
-
9
  let _spDcCache = null;
10
 
 
 
 
 
11
  function getSpDc() {
12
  if (_spDcCache) return _spDcCache;
13
 
14
- // 1. Prefer env var
15
- if (process.env.SP_DC && process.env.SP_DC !== 'undefined') {
16
- _spDcCache = process.env.SP_DC;
17
- return _spDcCache;
18
- }
19
-
20
- // 2. Fall back to cookies.txt
21
  try {
22
  const cookiePath = new URL('../cookies.txt', import.meta.url).pathname;
23
  const text = fs.readFileSync(cookiePath, 'utf8');
@@ -26,16 +20,14 @@ function getSpDc() {
26
  const parts = line.split('\t');
27
  if (parts.length >= 7 && parts[5] === 'sp_dc') {
28
  _spDcCache = parts[6].trim();
29
- console.log('sp_dc loaded from cookies.txt');
30
  return _spDcCache;
31
  }
32
  }
33
- } catch (_) {
34
- // cookies.txt not found or unreadable
35
  }
36
 
37
- console.warn('Warning: sp_dc not found in env or cookies.txt');
38
- return undefined;
39
  }
40
  const DEFAULT_SECRETS_URL = "https://git.gay/thereallo/totp-secrets/raw/branch/main/secrets/secretDict.json";
41
  const FALLBACK_SECRETS_URL = "https://raw.githubusercontent.com/xyloflake/spot-secrets-go/refs/heads/main/secrets/secretDict.json";
 
1
  import axios from "axios";
2
  import * as OTPAuth from "otpauth";
 
3
  import fs from "fs";
4
  import { fileURLToPath } from "url";
5
 
 
 
6
  let _spDcCache = null;
7
 
8
+ export function updateSpDc(value) {
9
+ _spDcCache = value;
10
+ }
11
+
12
  function getSpDc() {
13
  if (_spDcCache) return _spDcCache;
14
 
 
 
 
 
 
 
 
15
  try {
16
  const cookiePath = new URL('../cookies.txt', import.meta.url).pathname;
17
  const text = fs.readFileSync(cookiePath, 'utf8');
 
20
  const parts = line.split('\t');
21
  if (parts.length >= 7 && parts[5] === 'sp_dc') {
22
  _spDcCache = parts[6].trim();
 
23
  return _spDcCache;
24
  }
25
  }
26
+ } catch (e) {
27
+ console.error('Failed to read sp_dc from cookies.txt:', e.message);
28
  }
29
 
30
+ throw new Error('sp_dc not found in cookies.txt — please update the file.');
 
31
  }
32
  const DEFAULT_SECRETS_URL = "https://git.gay/thereallo/totp-secrets/raw/branch/main/secrets/secretDict.json";
33
  const FALLBACK_SECRETS_URL = "https://raw.githubusercontent.com/xyloflake/spot-secrets-go/refs/heads/main/secrets/secretDict.json";
services/spotifyCanvasService.js CHANGED
@@ -25,7 +25,7 @@ export async function getCanvases(trackUri) {
25
  'Accept-Language': 'en',
26
  'User-Agent': 'Spotify/9.0.34.593 iOS/18.4 (iPhone15,3)',
27
  'Accept-Encoding': 'gzip, deflate, br',
28
- 'Authorization': `Bearer ${accessToken}`,
29
  },
30
  }
31
  );
 
25
  'Accept-Language': 'en',
26
  'User-Agent': 'Spotify/9.0.34.593 iOS/18.4 (iPhone15,3)',
27
  'Accept-Encoding': 'gzip, deflate, br',
28
+ 'Authorization': `Bearer ${accessToken}`,
29
  },
30
  }
31
  );