-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
225 lines (195 loc) · 9.32 KB
/
index.html
File metadata and controls
225 lines (195 loc) · 9.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Apple2Spotify</title>
<style>
body { font-family: sans-serif; max-width: 800px; margin: auto; padding: 20px; background-color: #f9f9f9; }
h1 { text-align: center; color: #ff2d55; }
input[type=text] { width: 100%; padding: 12px; margin: 10px 0; border: 1px solid #ddd; border-radius: 8px; }
button { padding: 12px 20px; margin: 5px 0; background-color: #ff2d55; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; font-weight: bold; transition: 0.3s; }
button:hover { background-color: #d82447; transform: scale(1.02); }
button:disabled { background-color: #ccc; cursor: not-allowed; }
#trackList { max-height: 350px; overflow-y: auto; border: 1px solid #ddd; padding: 15px; margin-top: 15px; border-radius: 8px; background-color: white; box-shadow: inset 0 2px 4px rgba(0,0,0,0.05); }
.track { display: flex; align-items: center; padding: 8px; border-bottom: 1px solid #eee; }
.track:last-child { border-bottom: none; }
.track label { flex: 1; cursor: pointer; margin-left: 10px; }
#log { white-space: pre-wrap; word-break: break-all; background-color: #222; color: #00ff00; padding: 15px; border-radius: 8px; margin-top: 15px; font-family: monospace; font-size: 12px; }
</style>
</head>
<body>
<h1>Apple Music → Spotify (ULTRA-VACUUM 👑 2.2)</h1>
<p style="text-align: center;">Paste your "Snatched" JSON or official Apple JSON below! ✨</p>
<label>
Spotify Playlist Name:
<input type="text" id="spotifyPlaylistName" placeholder="My Snatched Playlist 🎧">
</label>
<div style="display: flex; gap: 10px; justify-content: center; flex-wrap: wrap;">
<button id="spotifyLogin">Login to Spotify</button>
<button id="fetchApple">1. PASTE JSON & PARSE</button>
<button id="transfer" disabled>2. Transfer to Spotify</button>
</div>
<div id="trackList"></div>
<pre id="log">Waiting for orders, johnball589... 💅</pre>
<script>
const SPOTIFY_CLIENT_ID = "52dbb7368d80433194dc029bf4f71137";
const REDIRECT_URI = "https://rosics-code.github.io/apple2spotify/index.html";
let spotifyToken = localStorage.getItem("spotify_access_token");
let spotifyUserId = null;
let appleTracks = [];
const log = msg => document.getElementById("log").textContent += msg + "\n";
const clearLog = () => document.getElementById("log").textContent = "";
// --- UTILS ---
const cleanString = (str) => {
if (!str) return "";
return str
.replace(/\(feat\..*?\)/gi, '')
.replace(/\[feat\..*?\]/gi, '')
.replace(/\(Explicit\)/gi, '')
.replace(/\[Explicit\]/gi, '')
.replace(/\s+E\s*$/, '') // Remove trailing 'E' from web scraping
.trim();
};
// --- SPOTIFY AUTH (Standard PKCE) ---
// (Keeping your original logic but fixing the Uint8Array typo and URLs)
async function generatePKCE() {
const verifier = Array.from(crypto.getRandomValues(new Uint8Array(64))).map(c => ('00' + c.toString(16)).slice(-2)).join("");
const challenge = btoa(String.fromCharCode.apply(null, new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
return { verifier, challenge };
}
document.getElementById("spotifyLogin").onclick = async () => {
const { verifier, challenge } = await generatePKCE();
sessionStorage.setItem("pkce_verifier", verifier);
window.location.href = `https://accounts.spotify.com/authorize?response_type=code&client_id=${SPOTIFY_CLIENT_ID}&scope=playlist-modify-private%20playlist-modify-public%20user-read-private&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&code_challenge_method=S256&code_challenge=${challenge}`;
};
// --- PARSER (THE BRAINS) ---
const parseAppleJson = (rawJsonString) => {
if (appleTracks.length === 0) clearLog();
log("🧐 Analyzing the JSON you snatched...");
try {
const jsonData = JSON.parse(rawJsonString);
let foundCount = 0;
const existingTrackMap = new Set(appleTracks.map(t => `${t.name.toLowerCase()}|${t.artist.toLowerCase()}`));
// This function handles BOTH the deep official JSON and your bookmarklet's "fakeJson"
const extract = (obj) => {
if (!obj || typeof obj !== 'object') return;
// Check if this object is a song (Works for official AND your bookmarklet)
if (obj.type === 'songs' || obj.type === 'library-songs') {
const name = obj.attributes?.name;
const artist = obj.attributes?.artistName;
if (name && artist) {
const cName = cleanString(name);
const cArtist = cleanString(artist);
const key = `${cName.toLowerCase()}|${cArtist.toLowerCase()}`;
if (!existingTrackMap.has(key)) {
appleTracks.push({ name: cName, artist: cArtist, rawName: name });
existingTrackMap.add(key);
foundCount++;
}
}
}
// Recurse through everything else
for (const key in obj) {
if (typeof obj[key] === 'object') extract(obj[key]);
}
};
extract(jsonData);
if (foundCount > 0) {
log(`✅ Success! Snatched ${foundCount} new tracks.`);
renderTrackList();
} else {
log("🤔 No new songs found. Make sure you copied the WHOLE JSON!");
}
document.getElementById("transfer").disabled = !spotifyToken;
} catch (e) {
log(`❌ Fail: That wasn't valid JSON. Try copying again!`);
}
};
const renderTrackList = () => {
const list = document.getElementById("trackList");
list.innerHTML = "";
appleTracks.forEach((t, i) => {
const div = document.createElement("div");
div.className = "track";
div.innerHTML = `<input type="checkbox" id="track${i}" checked><label for="track${i}"><b>${t.name}</b> — ${t.artist}</label>`;
list.appendChild(div);
});
};
document.getElementById("fetchApple").onclick = () => {
const data = prompt("Paste your JSON here, king:");
if (data) parseAppleJson(data);
};
// --- TRANSFER ---
document.getElementById("transfer").onclick = async () => {
const selected = appleTracks.filter((t, i) => document.getElementById(`track${i}`).checked);
const pName = document.getElementById("spotifyPlaylistName").value.trim() || "Snatched from Apple";
log(`🚀 Starting transfer of ${selected.length} bangers...`);
try {
// 1. Create Playlist
const pResp = await fetch(`https://api.spotify.com/v1/users/${spotifyUserId}/playlists`, {
method: "POST",
headers: { Authorization: `Bearer ${spotifyToken}`, "Content-Type": "application/json" },
body: JSON.stringify({ name: pName, public: false })
});
const playlist = await pResp.json();
const uris = [];
for (const t of selected) {
// Improved search query
const query = encodeURIComponent(`track:${t.name} artist:${t.artist}`);
const sResp = await fetch(`https://api.spotify.com/v1/search?q=${query}&type=track&limit=5`, {
headers: { Authorization: `Bearer ${spotifyToken}` }
});
const sData = await sResp.json();
if (sData.tracks?.items?.length) {
// Find explicit version first, otherwise take top result
const match = sData.tracks.items.find(i => i.explicit) || sData.tracks.items[0];
uris.push(match.uri);
} else {
log(`⚠️ Missed: ${t.name} (Spotify couldn't find it)`);
}
}
// 2. Add in chunks
for (let i = 0; i < uris.length; i += 100) {
await fetch(`https://api.spotify.com/v1/playlists/${playlist.id}/tracks`, {
method: "POST",
headers: { Authorization: `Bearer ${spotifyToken}`, "Content-Type": "application/json" },
body: JSON.stringify({ uris: uris.slice(i, i + 100) })
});
}
log(`\n🎉 DONE! ${uris.length} tracks added to "${pName}". Go vibe! 🎧`);
} catch (e) {
log(`❌ Error: ${e.message}`);
}
};
// Check for Auth Code on load
window.onload = async () => {
const code = new URLSearchParams(window.location.search).get("code");
if (code) {
const verifier = sessionStorage.getItem("pkce_verifier");
const resp = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ client_id: SPOTIFY_CLIENT_ID, grant_type: "authorization_code", code, redirect_uri: REDIRECT_URI, code_verifier: verifier })
});
const data = await resp.json();
if (data.access_token) {
spotifyToken = data.access_token;
localStorage.setItem("spotify_access_token", spotifyToken);
window.history.replaceState({}, document.title, REDIRECT_URI);
}
}
if (spotifyToken) {
const uResp = await fetch("https://api.spotify.com/v1/me", { headers: { Authorization: `Bearer ${spotifyToken}` } });
if (uResp.ok) {
const uData = await uResp.json();
spotifyUserId = uData.id;
document.getElementById("spotifyLogin").style.display = "none";
log(`✅ Logged in as ${uData.display_name}. Ready to snatch!`);
} else {
localStorage.removeItem("spotify_access_token");
}
}
};
</script>
</body>
</html>