from flask import Flask, render_template, send_from_directory, jsonify, request, redirect, session
from dotenv import load_dotenv
import os
import requests
import base64
import json

load_dotenv()  # Explicitly load the environment variables from .env file

app = Flask(__name__)
app.secret_key = os.urandom(24)

@app.route('/')
def home():
    audio_files = os.listdir('static/audio')
    audio_files = [file for file in audio_files if file.endswith('.mp3')]
    return render_template('index.html', audio_files=audio_files)

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico')

@app.route('/audio/<path:filename>')
def audio(filename):
    try:
        return send_from_directory('static/audio', filename)
    except Exception as e:
        print(f"Error serving audio file: {e}")
        return "Audio file not found", 404

@app.route('/login')
def login():
    auth_url = "https://accounts.spotify.com/authorize"
    client_id = os.getenv('SPOTIFY_CLIENT_ID')
    redirect_uri = os.getenv('SPOTIFY_REDIRECT_URI')
    scope = "streaming user-read-email user-read-private user-modify-playback-state user-read-playback-state"
    return redirect(f"{auth_url}?response_type=code&client_id={client_id}&scope={scope}&redirect_uri={redirect_uri}")

@app.route('/callback')
def callback():
    code = request.args.get('code')
    token_url = "https://accounts.spotify.com/api/token"
    client_id = os.getenv('SPOTIFY_CLIENT_ID')
    client_secret = os.getenv('SPOTIFY_CLIENT_SECRET')
    redirect_uri = os.getenv('SPOTIFY_REDIRECT_URI')

    auth_str = f"{client_id}:{client_secret}"
    b64_auth_str = base64.urlsafe_b64encode(auth_str.encode()).decode()

    headers = {
        "Authorization": f"Basic {b64_auth_str}"
    }
    data = {
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": redirect_uri
    }

    response = requests.post(token_url, headers=headers, data=data)
    response_data = response.json()

    session['access_token'] = response_data.get('access_token')
    session['refresh_token'] = response_data.get('refresh_token')

    # Fetch user's playlists
    playlists_url = "https://api.spotify.com/v1/me/playlists"
    headers = {
        "Authorization": f"Bearer {session['access_token']}"
    }
    playlists_response = requests.get(playlists_url, headers=headers)
    playlists = playlists_response.json()

    # Find the most recently added track and its playlist
    most_recent_playlist = None
    most_recent_added_at = None

    for playlist in playlists['items']:
        playlist_tracks_url = playlist['tracks']['href']
        tracks_response = requests.get(playlist_tracks_url, headers=headers)
        tracks = tracks_response.json()

        for item in tracks['items']:
            added_at = item['added_at']
            if most_recent_added_at is None or added_at > most_recent_added_at:
                most_recent_added_at = added_at
                most_recent_playlist = playlist

    if most_recent_playlist:
        session['top_playlist_id'] = most_recent_playlist['id']
        session['top_playlist_uri'] = most_recent_playlist['uri']

    return redirect('/')

@app.route('/spotify_token')
def spotify_token():
    return jsonify(
        access_token=session.get('access_token'),
        top_playlist_uri=session.get('top_playlist_uri')
    )

if __name__ == '__main__':
    flask_env = os.getenv('FLASK_ENV')
    debug_mode = flask_env == 'development'
    app.run(debug=debug_mode)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3D Audio Visualizer</title>
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}">
    <style>
        body {
            margin: 0;
            overflow: hidden;
            display: flex;
            justify-content: center;
            align-items: center;
            height: fit-content;
            background-color: #000;
            flex-direction: column;
        }
        #startButton {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #fff;
            border: none;
            cursor: pointer;
            margin-bottom: 10px;
        }
        #audioPlayer {
            display: none;
            align-items: center;
            justify-content: center;
            color: #fff;
            margin-bottom: 0px;
        }
        #playPauseButton {
            margin-right: 10px;
            padding: 10px 20px;
            font-size: 16px;
            background-color: #fff;
            border: none;
            cursor: pointer;
        }
        #currentTime, #duration {
            margin: 0 5px;
        }
        canvas {
            display: block;
        }
        #audioSelect {
            margin-bottom: 10px;
        }
        #spotifyLogin {
            margin-top: 10px;
            padding: 10px 20px;
            font-size: 16px;
            background-color: #1DB954;
            color: #fff;
            border: none;
            cursor: pointer;
        }
        #spotifyPlayerContainer {
            display: none;
            flex-direction: column;
            align-items: center;
        }
        #spotifyIframe {
            width: 300px;
            height: 380px;
            border: none;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <select id="audioSelect">
        {% for file in audio_files %}
            <option value="{{ file }}">{{ file }}</option>
        {% endfor %}
    </select>
    <button id="startButton">Start Audio</button>
    <div id="audioPlayer">
        <button id="playPauseButton">Play</button>
        <span id="currentTime">0:00</span> / <span id="duration">0:00</span>
    </div>
    <audio id="audio">
        <source id="audioSource" src="{{ url_for('audio', filename=audio_files[0]) }}" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>
    <a href="/login" id="spotifyLogin">Login to Spotify</a>
    <div id="spotifyPlayerContainer">
        <iframe id="spotifyIframe" src="" allow="encrypted-media"></iframe>
    </div>
    <script src="{{ url_for('static', filename='js/simplex-noise.js') }}"></script>
    <script src="https://sdk.scdn.co/spotify-player.js"></script>
    <script type="module" src="{{ url_for('static', filename='js/visualizer.js') }}"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            window.onSpotifyWebPlaybackSDKReady = () => {
                fetch('/spotify_token')
                    .then(response => response.json())
                    .then(data => {
                        const token = data.access_token;
                        const topPlaylistUri = data.top_playlist_uri;
                        const player = new Spotify.Player({
                            name: '3D Audio Visualizer',
                            getOAuthToken: cb => { cb(token); },
                            volume: 0.5
                        });

                        player.addListener('ready', ({ device_id }) => {
                            console.log('Ready with Device ID', device_id);
                            document.getElementById('spotifyPlayerContainer').style.display = 'flex';
                            document.getElementById('spotifyIframe').src = https://open.spotify.com/embed/playlist/${topPlaylistUri.split(':')[2]}?utm_source=generator;

                            player.resume().then(() => {
                                console.log('Resumed Spotify Playback');
                            });

                            fetch(https://api.spotify.com/v1/me/player/play, {
                                method: 'PUT',
                                headers: {
                                    'Authorization': Bearer ${token},
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({
                                    "device_ids": [device_id],
                                    "play": true,
                                    "context_uri": topPlaylistUri
                                })
                            })
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error(HTTP error! status: ${response.status});
                                }
                            })
                            .catch(error => {
                                console.error('Error playing Spotify playlist:', error);
                            });

                            // Connect Spotify audio to the visualizer
                            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                            const analyser = audioContext.createAnalyser();
                            analyser.fftSize = 256;
                            const bufferLength = analyser.frequencyBinCount;
                            const dataArray = new Uint8Array(bufferLength);

                            fetch(https://api.spotify.com/v1/me/player, {
                                method: 'PUT',
                                headers: {
                                    'Authorization': Bearer ${token},
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({
                                    "device_ids": [device_id],
                                    "play": true,
                                    "context_uri": topPlaylistUri
                                })
                            })
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error(HTTP error! status: ${response.status});
                                }
                            })
                            .catch(error => {
                                console.error('Error playing Spotify playlist:', error);
                            });

                            const spotifyPlayer = document.getElementById('spotifyIframe');

                            const spotifySourceNode = audioContext.createMediaElementSource(spotifyPlayer);
                            spotifySourceNode.connect(analyser);
                            analyser.connect(audioContext.destination);

                            function updateVisualizer() {
                                analyser.getByteFrequencyData(dataArray);
                                visualizer.update(dataArray);
                                requestAnimationFrame(updateVisualizer);
                            }
                            updateVisualizer();
                        });

                        player.addListener('not_ready', ({ device_id }) => {
                            console.log('Device ID has gone offline', device_id);
                        });

                        player.addListener('player_state_changed', state => {
                            console.log(state);
                            if (state.paused) {
                                visualizer.pause();
                            } else {
                                visualizer.play();
                            }
                        });

                        player.connect();
                    })
                    .catch(error => {
                        console.error('Error fetching Spotify token', error);
                    });
            };
        });
    </script>
</body>
</html>


import * as THREE from './three.module.js';
import { OrbitControls } from './OrbitControls.js';

document.addEventListener('DOMContentLoaded', function () {
    console.log('DOM fully loaded and parsed');

    // Initialize Three.js
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    console.log('Three.js scene, camera, and renderer initialized');

    // Initialize OrbitControls
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    controls.dampingFactor = 1.5;
    controls.screenSpacePanning = false;
    controls.maxPolarAngle = Math.PI / 1;

    console.log('OrbitControls initialized');

    // Create geometry for visualizer with higher resolution
    const geometry = new THREE.SphereGeometry(1, 500, 500);
    const material = new THREE.MeshBasicMaterial({ vertexColors: true });
    const sphere = new THREE.Mesh(geometry, material);
    scene.add(sphere);

    sphere.position.y = 0.145;
    camera.position.z = 3.5;

    console.log('Sphere geometry created and added to scene');

    // Helper function to convert HSL to RGB
    function hslToRgb(h, s, l) {
        let r, g, b;
        if (s == 0) {
            r = g = b = l;
        } else {
            const hue2rgb = function(p, q, t) {
                if (t < 0) t += 1;
                if (t > 1) t -= 1;
                if (t < 1 / 6) return p + (q - p) * 6 * t;
                if (t < 1 / 2) return q;
                if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
                return p;
            };
            const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            const p = 2 * l - q;
            r = hue2rgb(p, q, h + 1 / 3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1 / 3);
        }
        return [r, g, b];
    }

    // Initialize vertex colors to HSL red (H:0, S:100%, L:75%)
    const h = 0;
    const s = 1;
    const l = 0.75;
    const [r, g, b] = hslToRgb(h, s, l);
    const colors = [];
    for (let i = 0; i < geometry.attributes.position.count; i++) {
        colors.push(r, g, b);
    }
    geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));

    console.log('Vertex colors initialized to HSL red');

    // Audio setup
    const audio = document.getElementById('audio');
    const audioSource = document.getElementById('audioSource');
    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
    const audioSourceNode = audioContext.createMediaElementSource(audio);
    const analyser = audioContext.createAnalyser();
    audioSourceNode.connect(analyser);
    analyser.connect(audioContext.destination);

    analyser.fftSize = 256;
    const bufferLength = analyser.frequencyBinCount;
    const dataArray = new Uint8Array(bufferLength);

    console.log('Audio context, source, and analyser initialized');

    const audioSelect = document.getElementById('audioSelect');
    const startButton = document.getElementById('startButton');
    const audioPlayer = document.getElementById('audioPlayer');
    const playPauseButton = document.getElementById('playPauseButton');
    const currentTimeElement = document.getElementById('currentTime');
    const durationElement = document.getElementById('duration');

    let isPlaying = false;
    let isPaused = false;

    audioSelect.addEventListener('change', () => {
        const selectedFile = audioSelect.value;
        audioSource.src = /audio/${selectedFile};
        audio.load();
        console.log(Audio source changed to: ${selectedFile});
        if (isPlaying) {
            audio.play();
        }
    });

    startButton.addEventListener('click', () => {
        audioContext.resume().then(() => {
            audio.play();
            startButton.style.display = 'none';
            audioPlayer.style.display = 'flex';
            console.log('AudioContext resumed and audio started');
            isPlaying = true;
            isPaused = false;
        }).catch((e) => {
            console.error('Error resuming AudioContext', e);
        });
    });

    playPauseButton.addEventListener('click', () => {
        if (audio.paused) {
            audio.play();
            playPauseButton.textContent = 'Pause';
            isPlaying = true;
            isPaused = false;
        } else {
            audio.pause();
            playPauseButton.textContent = 'Play';
            isPlaying = true;
            isPaused = true;
        }
    });

    audio.addEventListener('play', () => {
        console.log('Audio is playing');
        playPauseButton.textContent = 'Pause';
        isPlaying = true;
        isPaused = false;
    });

    audio.addEventListener('pause', () => {
        console.log('Audio is paused');
        playPauseButton.textContent = 'Play';
        isPlaying = true;
        isPaused = true;
    });

    audio.addEventListener('ended', () => {
        console.log('Audio ended');
        isPlaying = false;
        isPaused = false;
    });

    audio.addEventListener('timeupdate', () => {
        const currentTime = audio.currentTime;
        const duration = audio.duration;

        const currentMinutes = Math.floor(currentTime / 60);
        const currentSeconds = Math.floor(currentTime % 60).toString().padStart(2, '0');
        currentTimeElement.textContent = ${currentMinutes}:${currentSeconds};

        if (!isNaN(duration)) {
            const durationMinutes = Math.floor(duration / 60);
            const durationSeconds = Math.floor(duration % 60).toString().padStart(2, '0');
            durationElement.textContent = ${durationMinutes}:${durationSeconds};
        }
    });

    audio.addEventListener('error', (e) => {
        console.error('Error playing audio', e);
    });

    // Initialize SimplexNoise instance for Perlin-like noise
    const simplex = new SimplexNoise();

    // Helper function to generate Perlin noise data
    const noiseDataArray = new Float32Array(bufferLength);
    function generatePerlinNoise() {
        const time = Date.now() * 0.0001;
        for (let i = 0; i < bufferLength; i++) {
            noiseDataArray[i] = (simplex.noise2D(i / 100, time) + 1) * 127.5;
        }
        return new Uint8Array(noiseDataArray);
    }

    // Initialize a moving average buffer
    const movingAverageBuffer = new Array(bufferLength).fill(0);
    const movingAverageSize = 10;

    // Function to apply moving average smoothing
    function applyMovingAverage(dataArray) {
        for (let i = 0; i < bufferLength; i++) {
            movingAverageBuffer[i] += (dataArray[i] - movingAverageBuffer[i]) / movingAverageSize;
            dataArray[i] = movingAverageBuffer[i];
        }
    }

    let autoRotate = true;

    // Add event listeners for mouse actions to control auto rotation
    renderer.domElement.addEventListener('mousedown', () => {
        autoRotate = false;
    });

    renderer.domElement.addEventListener('mouseup', () => {
        autoRotate = true;
    });

    renderer.domElement.addEventListener('touchstart', () => {
        autoRotate = false;
    });

    renderer.domElement.addEventListener('touchend', () => {
        autoRotate = true;
    });

    // Render loop
    function animate() {
        requestAnimationFrame(animate);

        if (isPlaying && !isPaused) {
            analyser.getByteFrequencyData(dataArray);
            applyMovingAverage(dataArray);
        } else if (!isPlaying) {
            dataArray.set(generatePerlinNoise());
            applyMovingAverage(dataArray);
        }

        const positions = sphere.geometry.attributes.position.array;
        const colors = sphere.geometry.attributes.color.array;
        for (let i = 0; i < positions.length; i += 3) {
            const vertex = new THREE.Vector3(
                positions[i],
                positions[i + 1],
                positions[i + 2]
            );
            vertex.normalize();

            const frequencyIndex = Math.floor((i / 3) % bufferLength);
            const magnitude = dataArray[frequencyIndex] / 150;

            const transformedMagnitude = Math.pow(magnitude, 1);
            const scale = 1 + transformedMagnitude * 0.5;

            vertex.multiplyScalar(scale);

            positions[i] = vertex.x;
            positions[i + 1] = vertex.y;
            positions[i + 2] = vertex.z;

            const hue = transformedMagnitude;
            const rgb = hslToRgb(hue, 1.0, 0.75);
            colors[i] = rgb[0];
            colors[i + 1] = rgb[1];
            colors[i + 2] = rgb[2];
        }

        sphere.geometry.attributes.position.needsUpdate = true;
        sphere.geometry.attributes.color.needsUpdate = true;

        if (autoRotate) {
            sphere.rotation.x += 0.0015;
            sphere.rotation.y += 0.0015;
            sphere.rotation.z += 0.0015;
        }

        controls.update();
        renderer.render(scene, camera);
    }

    animate();

    // Resize listener
    window.addEventListener('resize', () => {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
    });

    // Spotify Player Setup
    window.onSpotifyWebPlaybackSDKReady = () => {
        fetch('/spotify_token')
            .then(response => response.json())
            .then(data => {
                const token = data.access_token;
                const topPlaylistUri = data.top_playlist_uri;
                const player = new Spotify.Player({
                    name: '3D Audio Visualizer',
                    getOAuthToken: cb => { cb(token); },
                    volume: 0.5
                });

                player.addListener('ready', ({ device_id }) => {
                    console.log('Ready with Device ID', device_id);
                    document.getElementById('spotifyPlayerContainer').style.display = 'flex';
                    document.getElementById('spotifyIframe').src = https://open.spotify.com/embed/playlist/${topPlaylistUri.split(':')[2]}?utm_source=generator;

                    player.resume().then(() => {
                        console.log('Resumed Spotify Playback');
                    });

                    fetch(https://api.spotify.com/v1/me/player/play, {
                        method: 'PUT',
                        headers: {
                            'Authorization': Bearer ${token},
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            "device_ids": [device_id],
                            "play": true,
                            "context_uri": topPlaylistUri
                        })
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(HTTP error! status: ${response.status});
                        }
                    })
                    .catch(error => {
                        console.error('Error playing Spotify playlist:', error);
                    });

                    const spotifyPlayer = document.getElementById('spotifyIframe');

                    const spotifySourceNode = audioContext.createMediaElementSource(spotifyPlayer);
                    spotifySourceNode.connect(analyser);
                    analyser.connect(audioContext.destination);

                    function updateVisualizer() {
                        analyser.getByteFrequencyData(dataArray);
                        visualizer.update(dataArray);
                        requestAnimationFrame(updateVisualizer);
                    }
                    updateVisualizer();
                });

                player.addListener('not_ready', ({ device_id }) => {
                    console.log('Device ID has gone offline', device_id);
                });

                player.addListener('player_state_changed', state => {
                    console.log(state);
                    if (state.paused) {
                        pauseVisualizer();
                    } else {
                        playVisualizer();
                    }
                });

                player.connect();
            })
            .catch(error => {
                console.error('Error fetching Spotify token', error);
            });
    };

    function playVisualizer() {
        if (audioContext.state === 'suspended') {
            audioContext.resume();
        }
        isPlaying = true;
        isPaused = false;
    }

    function pauseVisualizer() {
        isPlaying = false;
        isPaused = true;
    }
});