User Tools

Site Tools


python:deezer-album-tracker

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
python:deezer-album-tracker [2024/03/29 19:13] Wulf Rajekpython:deezer-album-tracker [2024/04/21 20:05] (current) Wulf Rajek
Line 25: Line 25:
 Example output: Example output:
 <code> <code>
-./dat.py  +$ /dat.py --days 7 
-Albums released in the past 6 months: +Albums released in the past 7 days:
-Release Date: 2024-01-12 +
-Artist: Papa Roach +
-Album Name: Scars (feat. Chris Daughtry) (Live)+
  
-Release Date: 2023-11-03 +Release Date: 2024-04-19 
-Artist: Limp Bizkit +Artist: Staind 
-Album Name: Counterfeit Countdown+Album Name: Better Days (feat. Dorothy) (1 track) 
 +Link: https://www.deezer.com/album/571491071 
 + 
 +Release Date: 2024-04-19 
 +Artist: Distilled Harmony 
 +Album Name: Nova (3 tracks) 
 +Link: https://www.deezer.com/album/572632871 
 + 
 +Release Date: 2024-04-19 
 +Artist: Taylor Swift 
 +Album Name: THE TORTURED POETS DEPARTMENT [EXPLICIT] (16 tracks) 
 +Link: https://www.deezer.com/album/574109801
  
-Release Date: 2023-10-31 
-Artist: Papa Roach 
-Album Name: Leave a Light On (Talk Away The Dark) 
 </code> </code>
  
Line 83: Line 88:
 import time import time
 import argparse import argparse
-from fuzzywuzzy import fuzz +from fuzzywuzzy import fuzzprocess
-from fuzzywuzzy import process+
 import os import os
  
 # Constants for file paths # Constants for file paths
-CONFIG_FILE = "config.json"+CONFIG_FILENAME = "config.json" 
 +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) 
 +CONFIG_FILE = os.path.join(SCRIPT_DIR, CONFIG_FILENAME) 
  
 def load_config(): def load_config():
Line 96: Line 103:
             "global": {             "global": {
                 "days": "180"                 "days": "180"
-            },            +            },
             "email": {             "email": {
                 "smtp_server": "smtp.example.com",                 "smtp_server": "smtp.example.com",
Line 112: Line 119:
     with open(CONFIG_FILE, "r") as config_file:     with open(CONFIG_FILE, "r") as config_file:
         return json.load(config_file)         return json.load(config_file)
 +
  
 def save_config(config): def save_config(config):
Line 117: Line 125:
         json.dump(config, config_file, indent=4)         json.dump(config, config_file, indent=4)
  
-def send_email(subject, body, recipients):+ 
 +def send_email(body):
     config = load_config()     config = load_config()
     email_config = config.get('email', {})     email_config = config.get('email', {})
Line 128: Line 137:
     sender_email = email_config.get('sender_email')     sender_email = email_config.get('sender_email')
     sender_password = email_config.get('sender_password')     sender_password = email_config.get('sender_password')
 +    email_subject = config.get('email_subject', 'Deezer Album Tracker')
  
     msg = MIMEMultipart()     msg = MIMEMultipart()
     msg['From'] = sender_email     msg['From'] = sender_email
     msg['To'] = ', '.join(email_config.get('email_recipients'))     msg['To'] = ', '.join(email_config.get('email_recipients'))
-    msg['Subject'] = f"{subject} - {datetime.now().strftime('%Y-%m-%d')}"+    msg['Subject'] = f"{email_subject} - {datetime.now().strftime('%Y-%m-%d')}"
  
     body = MIMEText(body)     body = MIMEText(body)
Line 146: Line 156:
         server.login(sender_email, sender_password)         server.login(sender_email, sender_password)
         server.send_message(msg)         server.send_message(msg)
 +
  
 def get_artist_name(artist_id): def get_artist_name(artist_id):
Line 154: Line 165:
         return data.get('name', '')         return data.get('name', '')
     return ''     return ''
 +
  
 def get_artist_id(artist_name): def get_artist_id(artist_name):
Line 165: Line 177:
     return None     return None
  
-def get_albums(artist_ids,lookupdays): + 
-    config = load_config()+def get_albums(artist_ids, lookupdays):
     base_url = "https://api.deezer.com/artist/{}/albums"     base_url = "https://api.deezer.com/artist/{}/albums"
     earliest_release = (datetime.now() - timedelta(days=lookupdays)).strftime('%Y-%m-%d')     earliest_release = (datetime.now() - timedelta(days=lookupdays)).strftime('%Y-%m-%d')
Line 172: Line 184:
     request_count = 0     request_count = 0
     start_time = time.time()     start_time = time.time()
 +
 +    today = datetime.today().strftime('%Y-%m-%d')
  
     for artist_id in artist_ids:     for artist_id in artist_ids:
Line 182: Line 196:
             for album in data['data']:             for album in data['data']:
                 release_date = datetime.strptime(album['release_date'], '%Y-%m-%d')                 release_date = datetime.strptime(album['release_date'], '%Y-%m-%d')
-                if release_date >= datetime.strptime(earliest_release, '%Y-%m-%d'):+                if (datetime.strptime(earliest_release, '%Y-%m-%d') <= release_date <= 
 +                        datetime.strptime(today, '%Y-%m-%d')): 
 +                    trackresponse = requests.get(album['tracklist']) 
 +                    request_count += 1 
 +                    if trackresponse.status_code == 200: 
 +                        tracklist = trackresponse.json() 
 +                        trackamount = tracklist['total'
 +                    else: 
 +                        trackamount = 0 
                     albums.append({                     albums.append({
                         'artist': artist_name,                         'artist': artist_name,
                         'album_name': album['title'],                         'album_name': album['title'],
-                        'release_date': album['release_date']+                        'release_date': album['release_date'], 
 +                        'trackamount': trackamount, 
 +                        'explicit_lyrics': album['explicit_lyrics'], 
 +                        'link': album['link']
                     })                     })
-                    +
         # Deezer rate limit is 50 requests / 5 seconds. Limiting to 40/5 here:         # Deezer rate limit is 50 requests / 5 seconds. Limiting to 40/5 here:
         # Check if 40 requests have been made in less than 5 seconds         # Check if 40 requests have been made in less than 5 seconds
Line 198: Line 224:
             request_count = 0             request_count = 0
             start_time = time.time()             start_time = time.time()
-                        +
     return sorted(albums, key=lambda x: x['release_date'], reverse=True)     return sorted(albums, key=lambda x: x['release_date'], reverse=True)
 +
  
 def list_artists(): def list_artists():
Line 207: Line 234:
     for artist_id, artist_name in sorted_artists.items():     for artist_id, artist_name in sorted_artists.items():
         print(f"{artist_name}  ({artist_id})")         print(f"{artist_name}  ({artist_id})")
 +
  
 def add_artist(artist_name): def add_artist(artist_name):
Line 218: Line 246:
     else:     else:
         print("Artist not found.")         print("Artist not found.")
 +
  
 def delete_artist(search_term): def delete_artist(search_term):
Line 227: Line 256:
     for index, (artist_name, score) in enumerate(choices):     for index, (artist_name, score) in enumerate(choices):
         print(f"{index + 1}. {artist_name} ({score})")         print(f"{index + 1}. {artist_name} ({score})")
-    choice_index int(input("Enter the number of the artist to delete: ")) - 1 +    choice_input = input("Enter the number of the artist to delete: ") 
-    if 0 <= choice_index < len(choices): +    if choice_input.isnumeric(): 
-        artist_name = choices[choice_index][0] +        choice_index = int(choice_input) - 1 
-        artist_id = [key for key, value in subscribed_artists.items() if value == artist_name][0] +        if 0 <= choice_index < len(choices): 
-        del config[artist_id] +            artist_name = choices[choice_index][0] 
-        save_config(config) +            artist_id = [key for key, value in subscribed_artists.items() if value == artist_name][0] 
-        print(f"Artist '{artist_name}' deleted successfully.")+            del config['artist_ids'][artist_id] 
 +            save_config(config) 
 +            print(f"Artist '{artist_name}' deleted successfully.") 
 +        else: 
 +            print("Invalid choice.")
     else:     else:
-        print("Invalid choice.")+        print("No number entered.") 
  
 def main(): def main():
Line 257: Line 291:
         artist_ids = config.get('artist_ids', [])         artist_ids = config.get('artist_ids', [])
         if args.days:         if args.days:
-            lookupdays=int(args.days)+            lookupdays = int(args.days)
         else:         else:
-            lookupdays=config.get('global', {})['days'+            lookupdays = config.get('global', {})['days'
-        albums = get_albums(artist_ids,lookupdays)+        albums = get_albums(artist_ids, lookupdays)
  
-        print(f"Albums released in the past {lookupdays} days:")+        output = f"Albums released in the past {lookupdays} days:\n\n"
         for album in albums:         for album in albums:
-            print("Release Date:", album['release_date']) +            output += f"Release Date: {album['release_date']}\n" 
-            print("Artist:", album['artist']) +            output += f"Artist: {album['artist']}\n" 
-            print("Album Name:", album['album_name']) +            output += f"Album Name: {album['album_name']}" 
-            print()+            if album['explicit_lyrics'] is True: 
 +                output += " [EXPLICIT]" 
 +            if album['trackamount'] > 0: 
 +                output += f" ({album['trackamount']} track" 
 +                if album['trackamount'] > 1: 
 +                    output += "s" 
 +                output += ")" 
 +            output += "\n" 
 +            output += f"Link: {album['link']}\n" 
 +            output += "\n" 
 +        print(output)
  
         if args.email:         if args.email:
-            email_subject = config.get('email_subject', 'Deezer Album Tracker'+            send_email(output
-            email_recipients = config.get('email_recipients', []) +
-            email_body = f"Albums released in the past {lookupdays} days:\n\n"+"\n".join([f"Release Date: {album['release_date']}\nArtist: {album['artist']}\nAlbum Name: {album['album_name']}\n" for album in albums]) +
-            send_email(email_subject, email_body, email_recipients)+
  
 if __name__ == "__main__": if __name__ == "__main__":
     main()     main()
 +
 </code> </code>
  
python/deezer-album-tracker.1711739623.txt.gz · Last modified: 2024/03/29 19:13 by Wulf Rajek