from flask import Flask, Response, jsonify from base64 import b64encode from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) import requests import json import os import random """ Inspired from https://github.com/natemoo-re """ print("Starting Server") SPOTIFY_CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID") SPOTIFY_SECRET_ID = os.getenv("SPOTIFY_SECRET_ID") SPOTIFY_REFRESH_TOKEN = os.getenv("SPOTIFY_REFRESH_TOKEN") SPOTIFY_URL_REFRESH_TOKEN = "https://accounts.spotify.com/api/token" SPOTIFY_URL_NOW_PLAYING = "https://api.spotify.com/v1/me/player/currently-playing" LATEST_PLAY = None app = Flask(__name__) def get_authorization(): return b64encode(f"{SPOTIFY_CLIENT_ID}:{SPOTIFY_SECRET_ID}".encode()).decode("ascii") def refresh_token(): data = { "grant_type": "refresh_token", "refresh_token": SPOTIFY_REFRESH_TOKEN, } headers = {"Authorization": "Basic {}".format(get_authorization())} response = requests.post(SPOTIFY_URL_REFRESH_TOKEN, data=data, headers=headers) repsonse_json = response.json() return repsonse_json["access_token"] def get_now_playing(): token = refresh_token() headers = {"Authorization": f"Bearer {token}"} response = requests.get(SPOTIFY_URL_NOW_PLAYING, headers=headers) if response.status_code == 204: return {} repsonse_json = response.json() return repsonse_json def get_svg_template(): css_bar = "" left = 1 for i in range(1, 76): anim = random.randint(350, 500) css_bar += ".bar:nth-child({}) {{{{ left: {}px; animation-duration: {}ms; }}}}".format( i, left, anim ) left += 4 svg = ( """ """ ) return svg def load_image_b64(url): resposne = requests.get(url) return b64encode(resposne.content).decode("ascii") def make_svg(data): global LATEST_PLAY template = get_svg_template() text = "Now playing" content_bar = "".join(["
" for i in range(75)]) if data == {} and LATEST_PLAY is not None: data = LATEST_PLAY text = "Latest play" content_bar = "" elif data == {}: content = """ """ return template.format(content) content = """