File size: 7,181 Bytes
dbdd344
2082b5c
e764825
dbdd344
9faaa03
 
dbdd344
cfbd08c
e764825
52a6c11
2082b5c
 
 
 
 
 
52a6c11
9faaa03
dbdd344
 
 
 
 
52a6c11
 
dbdd344
7507bae
52a6c11
9faaa03
 
b414958
9cf08d5
 
 
b414958
52a6c11
9cf08d5
2082b5c
e764825
f8df622
e764825
cfbd08c
e764825
 
 
cfbd08c
e764825
 
de17c6c
2082b5c
9cf08d5
2082b5c
de17c6c
e764825
cfbd08c
 
9cf08d5
2082b5c
e764825
cfbd08c
 
de17c6c
e764825
de17c6c
 
9cf08d5
cfbd08c
 
 
 
 
9cf08d5
cfbd08c
 
9cf08d5
cfbd08c
 
9cf08d5
 
7507bae
9cf08d5
cfbd08c
 
9cf08d5
e764825
cfbd08c
 
 
de17c6c
52a6c11
cfbd08c
34ae2ff
9cf08d5
671016b
52a6c11
2082b5c
9cf08d5
b6b5233
52a6c11
f8df622
52a6c11
f8df622
7507bae
cfbd08c
2082b5c
 
f8df622
52a6c11
2082b5c
9cf08d5
 
 
 
 
cfbd08c
e764825
52a6c11
f8df622
52a6c11
7507bae
 
f8df622
2082b5c
9cf08d5
2082b5c
 
e764825
9cf08d5
2082b5c
9cf08d5
 
 
 
 
 
 
 
 
 
 
 
e764825
9cf08d5
 
 
 
 
e764825
9cf08d5
 
 
 
cfbd08c
9cf08d5
2082b5c
 
cfbd08c
f8df622
52a6c11
e764825
de17c6c
 
 
e764825
de17c6c
 
 
2082b5c
e764825
de17c6c
e764825
 
de17c6c
e764825
de17c6c
e764825
 
 
 
 
9c0c6aa
 
cfbd08c
 
 
de17c6c
cfbd08c
e764825
 
 
2082b5c
f8df622
52a6c11
9c0c6aa
cfbd08c
b6b5233
e764825
 
 
 
 
b6b5233
f8df622
52a6c11
9cf08d5
 
52a6c11
9faaa03
 
de17c6c
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
import os
import json
import random
import gradio as gr
import spotipy
from spotipy.oauth2 import SpotifyOAuth

# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# Configuration
REDIRECT_URI = "https://jisaacso219-rng-shuffle.hf.space/"
SCOPE = (
    "streaming "
    "user-read-playback-state "
    "user-modify-playback-state "
    "playlist-read-private"
)
CLIENT_ID     = os.environ["SPOTIFY_CLIENT_ID"]
CLIENT_SECRET = os.environ["SPOTIFY_CLIENT_SECRET"]

sp_oauth = SpotifyOAuth(
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET,
    redirect_uri=REDIRECT_URI,
    scope=SCOPE,
    show_dialog=True,
)

sp = None
user_playlists = {}

def get_auth_url():
    url = sp_oauth.get_authorize_url()
    print("[SERVER] Auth URL:", url)
    return url

def check_login(code: str):
    print("[SERVER] check_login code:", code)
    global sp, user_playlists

    if not code:
        # still waiting for OAuth redirect
        return (
            gr.update(visible=False),  # status
            gr.update(visible=False),  # dropdown
            gr.update(visible=False),  # html_token
        )

    # Exchange code for token
    tokinfo      = sp_oauth.get_access_token(code, as_dict=True)
    access_token = tokinfo["access_token"]
    print("[SERVER] Received token:", access_token[:8], "…")
    sp = spotipy.Spotify(auth=access_token)

    # Fetch playlists
    items = sp.current_user_playlists(limit=50)["items"]
    user_playlists = {p["name"]: p["id"] for p in items}
    print("[SERVER] Playlists:", list(user_playlists.keys()))

    # Inject SDK + debug scripts + iframe escape
    sdk_js = f"""
    <script>
      if (window.self !== window.top) {{
        console.log("⚠️ Busting out of iframe…");
        window.top.location.href = window.location.href;
      }}
      console.log("[SDK] Setting ACCESS_TOKEN");
      window.ACCESS_TOKEN = "{access_token}";
    </script>
    <script src="https://sdk.scdn.co/spotify-player.js"></script>
    <script>
      window.onSpotifyWebPlaybackSDKReady = () => {{
        console.log("[SDK] SDK Ready");
        const player = new Spotify.Player({{
          name: 'RNG Web Player',
          getOAuthToken: cb => cb(window.ACCESS_TOKEN),
          volume: 0.5
        }});
        ['initialization_error','authentication_error','account_error','playback_error']
          .forEach(evt => player.addListener(evt, e => console.error('[SDK ' + evt + ']', e)));
        player.addListener('ready', ({{ device_id }}) => {{
          console.log('[SDK] Player ready, device_id:', device_id);
          window._webDeviceId = device_id;
        }});
        player.addListener('player_state_changed', state => console.log('[SDK] state_changed', state));
        player.connect().then(success => console.log('[SDK] connect()', success));
      }};
    </script>
    """

    return (
        gr.update(visible=True, value="βœ… Logged in! Choose a playlist below."),
        gr.update(visible=True, choices=list(user_playlists.keys())),
        gr.update(visible=True, value=sdk_js),
    )

def load_playlist_info(pl_name: str):
    print("[SERVER] load_playlist_info:", pl_name)
    pid  = user_playlists[pl_name]
    data = sp.playlist(pid)
    img   = data["images"][0]["url"] if data["images"] else ""
    owner = data["owner"]["display_name"]
    desc  = data.get("description", "")
    html  = f"""
      <img src="{img}" width="300" style="border-radius:8px;"/><br/>
      <strong>{pl_name}</strong> by {owner}<br/>{desc}
    """
    return html, gr.update(visible=True)

def shuffle_and_play(pl_name: str):
    print("[SERVER] shuffle_and_play:", pl_name)
    pid = user_playlists.get(pl_name)
    if not pid:
        print("[SERVER] No playlist selected")
        return gr.update(value="⚠️ No playlist selected.", visible=True)

    # Gather & shuffle URIs
    tracks, results = [], sp.playlist_tracks(pid)
    tracks.extend(results["items"])
    while results["next"]:
        results = sp.next(results)
        tracks.extend(results["items"])
    uris = [t["track"]["uri"] for t in tracks if t["track"]]
    random.shuffle(uris)
    print(f"[SERVER] Shuffled {len(uris)} tracks")

    uris_json = json.dumps(uris)
    play_js   = f"""
    <div id="player_debug" style="color:white;font-family:monospace;"></div>
    <script>
      console.log("[JS] Starting playback, device_id:", window._webDeviceId);
      console.log("[JS] URIs length:", {len(uris)});
      (async () => {{
        try {{
          const resp = await fetch(
            'https://api.spotify.com/v1/me/player/play?device_id=' + window._webDeviceId,
            {{
              method: 'PUT',
              headers: {{
                'Authorization': 'Bearer ' + window.ACCESS_TOKEN,
                'Content-Type': 'application/json'
              }},
              body: JSON.stringify({{uris:{uris_json}}})
            }}
          );
          const text = await resp.text();
          console.log("[JS] fetch status:", resp.status, text);
          document.getElementById("player_debug").innerText =
            `[JS] fetch status: ${{resp.status}} – ${{text}}`;
        }} catch(e) {{
          console.error("[JS] Playback error:", e);
          document.getElementById("player_debug").innerText =
            "[JS] Playback error: " + e;
        }}
      }})();
    </script>
    """
    return gr.update(value="▢️ Now playing in-browser!" + play_js, visible=True)

with gr.Blocks() as demo:
    # Auto-bust iframe on load
    gr.HTML("""
    <script>
      if (window.self !== window.top) {
        console.log("⚠️ Busting out of iframe on load");
        window.top.location.href = window.location.href;
      }
    </script>
    """)
    # Fallback link
    gr.HTML(
      '<a href="https://jisaacso219-rng-shuffle.hf.space/" '
      'target="_blank" style="font-size:16px;">πŸ”— Open standalone</a>'
    )
    gr.Markdown("After opening standalone, click **Step 1: Login to Spotify**…")

    # OAuth button (same tab)
    login_btn = gr.Button("πŸ” Step 1: Login to Spotify")
    login_btn.click(
        fn=None, inputs=None, outputs=None,
        js=f"() => window.location.href = '{get_auth_url()}'"
    )

    code_box   = gr.Textbox(visible=False, elem_id="auth_code")
    status     = gr.Markdown(visible=False)
    dropdown   = gr.Dropdown(choices=[], label="Step 2: Select a Playlist", visible=False)
    html_token = gr.HTML(visible=False)

    info_html  = gr.HTML(visible=False)
    shuffle_btn= gr.Button("πŸ”€ Step 3: Shuffle & Play", visible=False)
    result     = gr.HTML(visible=False)

    demo.load(
        fn=check_login,
        inputs=[code_box],
        outputs=[status, dropdown, html_token],
        js="""
        () => {
          const c = new URLSearchParams(window.location.search).get('code') || "";
          console.log("[JS] demo.load code:", c);
          return c;
        }
        """
    )

    dropdown.change(load_playlist_info, [dropdown], [info_html, shuffle_btn])
    shuffle_btn.click(shuffle_and_play, [dropdown], [result])

if __name__ == "__main__":
    demo.launch()