import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from PIL import Image
from time import sleep


# SpotifyWatch class

class SpotifyWatch:
    def __init__(self, client_id, client_secret):
        # Initialize the OAuth connection
        print("Initializing Spotify API connection.")
        scope = "user-read-currently-playing"
        self.sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=client_id,
                                                            client_secret=client_secret,
                                                            redirect_uri="http://google.com",
                                                            scope=scope))

        # Remember the metadata from the most recent successful check
        # Start with reasonable default values that will work in the other methods in the class

        # Track ID
        self.id = ""

        # Album cover
        self.cover = Image.new("RGB", (640, 640))

        # Title and artist
        self.title = ""
        self.artist = ""

    # Main method for retrieving the metadata of the currently-playing song & saving to disk
    # Returns True if there are changes to the metadata, False if not
    def update_metadata(self):
        # Get the currently-playing track metadata
        print("Retrieving current track metadata...")
        tr = self.sp.current_user_playing_track()

        # If there is no song playing, exit
        if tr is None:
            print("No song currently playing.")
            return False

        # If there are no changes, exit
        if tr['item']['id'] == self.id:
            print("No changes since last check. (Song ID: " + self.id + ")")
            return False

        # There are changes, so update the object's metadata:

        # Save the new Track ID
        self.id = tr['item']['id']

        # Retrieve the new image data from the album cover URL
        cover_url = tr["item"]["album"]["images"][0]["url"]
        self.cover = Image.open(requests.get(cover_url, stream=True).raw)

        # Save the new track title
        self.title = tr["item"]["name"]

        # There may be one or more artists, concatenate their names & delimit with commas
        self.artist = ', '.join([artist["name"] for artist in tr["item"]["artists"]])

        print("Now Playing:")
        print(self.title)
        print(self.artist)

        # Exit
        return True

    # Save the stored metadata to disk, for use in other applications (e.g. OBS)
    @staticmethod
    def ellipsis(string, max_len):
        if len(string) > max_len:
            string = string[0:max_len-3] + "..."
        return string

    def save_metadata(self):
        # Write the song title & artist to a text file
        file = open('songinfo.txt', 'w')
        file.write(self.ellipsis(self.title, 42))
        file.write('\n')
        file.write(self.ellipsis(self.artist, 42))
        file.close()

        # Save the album cover
        self.cover.save('cover.png')


# MAIN LOOP
if __name__ == "__main__":
    # Load the app credentials from file in the working directory
    # Should be a text file with one line: "<client_id>,<client_secret>"
    file = open('.credentials', 'r')
    client_id, client_secret = file.readline().split(',')

    # Create a persistent SpotifyWatch object
    bot = SpotifyWatch(client_id=client_id, client_secret=client_secret)

    # Main loop: Update metadata periodically
    delay = 15  # seconds
    try:
        while True:
            # Update the metadata
            update = bot.update_metadata()

            # Save to disk if needed
            if update:
                bot.save_metadata()

            # Wait
            sleep(delay)

    except KeyboardInterrupt:
        print("Exited by user.")

import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from PIL import Image
from time import sleep


# SpotifyWatch class

class SpotifyWatch:
    def __init__(self, client_id, client_secret):
        # Initialize the OAuth connection
        print("Initializing Spotify API connection.")
        scope = "user-read-currently-playing"
        self.sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=client_id,
                                                            client_secret=client_secret,
                                                            redirect_uri="http://google.com",
                                                            scope=scope))

        # Remember the metadata from the most recent successful check
        # Start with reasonable default values that will work in the other methods in the class

        # Track ID
        self.id = ""

        # Album cover
        self.cover = Image.new("RGB", (640, 640))

        # Title and artist
        self.title = ""
        self.artist = ""

    # Main method for retrieving the metadata of the currently-playing song & saving to disk
    # Returns True if there are changes to the metadata, False if not
    def update_metadata(self):
        # Get the currently-playing track metadata
        print("Retrieving current track metadata...")
        tr = self.sp.current_user_playing_track()

        # If there is no song playing, exit
        if tr is None:
            print("No song currently playing.")
            return False

        # If there are no changes, exit
        if tr['item']['id'] == self.id:
            print("No changes since last check. (Song ID: " + self.id + ")")
            return False

        # There are changes, so update the object's metadata:

        # Save the new Track ID
        self.id = tr['item']['id']

        # Retrieve the new image data from the album cover URL
        cover_url = tr["item"]["album"]["images"][0]["url"]
        self.cover = Image.open(requests.get(cover_url, stream=True).raw)

        # Save the new track title
        self.title = tr["item"]["name"]

        # There may be one or more artists, concatenate their names & delimit with commas
        self.artist = ', '.join([artist["name"] for artist in tr["item"]["artists"]])

        print("Now Playing:")
        print(self.title)
        print(self.artist)

        # Exit
        return True

    # Save the stored metadata to disk, for use in other applications (e.g. OBS)
    @staticmethod
    def ellipsis(string, max_len):
        if len(string) > max_len:
            string = string[0:max_len-3] + "..."
        return string

    def save_metadata(self):
        # Write the song title & artist to a text file
        file = open('songinfo.txt', 'w')
        file.write(self.ellipsis(self.title, 42))
        file.write('\n')
        file.write(self.ellipsis(self.artist, 42))
        file.close()

        # Save the album cover
        self.cover.save('cover.png')


# MAIN LOOP
if __name__ == "__main__":
    # Load the app credentials from file in the working directory
    # Should be a text file with one line: "<client_id>,<client_secret>"
    file = open('.credentials', 'r')
    client_id, client_secret = file.readline().split(',')

    # Create a persistent SpotifyWatch object
    bot = SpotifyWatch(client_id=client_id, client_secret=client_secret)

    # Main loop: Update metadata periodically
    delay = 15  # seconds
    try:
        while True:
            # Update the metadata
            update = bot.update_metadata()

            # Save to disk if needed
            if update:
                bot.save_metadata()

            # Wait
            sleep(delay)

    except KeyboardInterrupt:
        print("Exited by user.")

# SpotifyWatch class # Initialize the OAuth connection # Remember the metadata from the most recent successful check # Start with reasonable default values that will work in the other methods in the class # Track ID # Album cover # Title and artist # Main method for retrieving the metadata of the currently-playing song & saving to disk # Returns True if there are changes to the metadata, False if not # Get the currently-playing track metadata # If there is no song playing, exit # If there are no changes, exit # There are changes, so update the object's metadata: # Save the new Track ID # Retrieve the new image data from the album cover URL # Save the new track title # There may be one or more artists, concatenate their names & delimit with commas # Exit # Save the stored metadata to disk, for use in other applications (e.g. OBS) # Write the song title & artist to a text file # Save the album cover # MAIN LOOP # Load the app credentials from file in the working directory # Should be a text file with one line: "<client_id>,<client_secret>" # Create a persistent SpotifyWatch object # Main loop: Update metadata periodically # seconds # Update the metadata # Save to disk if needed # Wait