Tag: iTunesDataTools

  • iTunes Top Songs & Albums Purchases Python Script

    This Python script fetches and displays the current top songs or albums based on purchases from the iTunes Store. Users can select a category and the number of entries to view, with rankings clearly labeled to reflect purchase trends as of the check date.

    Click to view script…
    #!/usr/bin/env python3
    # iTunes Top Purchases Scraper
    # Purpose: Fetches and displays the current top songs or albums based on purchases from the iTunes Store.
    # Note: This script shows purchase-based rankings, not streaming data.
    
    import requests
    from datetime import datetime
    
    # Define categories with their display names and RSS feed paths
    categories = {
        1: {'name': 'Top Songs (Purchases)', 'path': 'topsongs'},
        2: {'name': 'Top Albums (Purchases)', 'path': 'topalbums'}
    }
    
    def main():
        """Main function to run the iTunes Top Purchases Scraper."""
        # Inform the user that the data reflects purchases, not streaming
        print("Welcome! This script shows top songs or albums based on purchases from the iTunes Store (not streaming data).")
        
        # Display category options
        print("\nSelect a category:")
        for key, value in categories.items():
            print(f"{key}. {value['name']}")
        
        # Get and validate category choice
        choice_input = input("Enter the number of your choice: ")
        try:
            choice = int(choice_input)
            if choice not in categories:
                raise ValueError
        except ValueError:
            print("Invalid choice. Please run the script again and enter 1 or 2.")
            return
        
        category = categories[choice]
        category_name = category['name']
        
        # Get and validate number of entries
        limit_input = input("Enter the number of entries to display (1-100, default 10): ")
        if limit_input.strip() == "":
            limit = 10
        else:
            try:
                limit = int(limit_input)
                if limit < 1 or limit > 100:
                    print("Limit must be between 1 and 100. Using default of 10.")
                    limit = 10
            except ValueError:
                print("Invalid input. Using default of 10.")
                limit = 10
        
        # Construct the RSS feed URL
        url = f"https://itunes.apple.com/us/rss/{category['path']}/limit={limit}/json"
        
        # Record the current date and time
        check_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # Fetch data from the iTunes RSS feed
        try:
            response = requests.get(url)
            response.raise_for_status()
            data = response.json()
        except requests.exceptions.RequestException as e:
            print(f"Error fetching data: {e}")
            return
        
        # Extract entries from the JSON response
        feed = data.get('feed', {})
        entries = feed.get('entry', [])
        
        if not entries:
            print("No data available for this category.")
            return
        
        # Display the results
        print(f"\n{category_name} as of {check_date}")
        print(f"{'Rank':<5} {'Name':<50} {'Artist':<30}")
        print("-" * 85)
        
        for i, entry in enumerate(entries, start=1):
            name = entry.get('im:name', {}).get('label', 'N/A')
            artist = entry.get('im:artist', {}).get('label', 'N/A')
            print(f"{i:<5} {name:<50} {artist:<30}")
    
    if __name__ == '__main__':
        main()
  • iOS App Store Comparison Tool Python Script

    This Python script enables users to compare multiple iOS apps by inputting their names, retrieving details like ratings, versions, and descriptions from the iTunes Search API. It displays a side-by-side overview of each app’s name, short description, rating count, rating stars, current version, and the date the check was initiated.

    Click to view script…
    import requests
    from datetime import datetime
    
    # Initialize a list to store app names
    app_names = []
    while True:
        app_name = input("Enter app name: ")
        app_names.append(app_name)
        another = input("Do you want to add another app? (y/n): ").lower()
        if another != 'y':
            break
    
    # Record the current date and time when the check is initiated
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # Initialize a list to store app data
    apps_data = []
    
    # Query the iTunes Search API for each app
    for app_name in app_names:
        try:
            response = requests.get(
                "https://itunes.apple.com/search",
                params={"term": app_name, "country": "us", "media": "software"}
            )
            response.raise_for_status()  # Raise an exception for HTTP errors
            data = response.json()
    
            if data["resultCount"] > 0:
                # Take the first result as the most relevant app
                app = data["results"][0]
                
                # Create a short description from the first 20 words of the full description
                words = app["description"].split()
                short_description = " ".join(words[:20]) + "..." if len(words) > 20 else " ".join(words)
                
                # Get the rating stars, formatting to one decimal place if available
                rating_stars = app.get("averageUserRating", "N/A")
                if rating_stars != "N/A":
                    rating_stars = f"{rating_stars:.1f}"
                
                # Compile the app information
                app_info = {
                    "app_name": app["trackName"],
                    "short_description": short_description,
                    "rating_count": app.get("userRatingCount", 0),
                    "rating_stars": rating_stars,
                    "current_version": app.get("version", "N/A"),
                    "check_date": current_time
                }
            else:
                app_info = {
                    "app_name": app_name,
                    "error": "App not found"
                }
        except requests.exceptions.RequestException as e:
            app_info = {
                "app_name": app_name,
                "error": f"Error fetching data: {e}"
            }
        
        apps_data.append(app_info)
    
    # Display the information for all apps
    for app_info in apps_data:
        if "error" in app_info:
            print(f"App Name: {app_info['app_name']}")
            print(f"Error: {app_info['error']}")
        else:
            print(f"App Name: {app_info['app_name']}")
            print(f"Short Description: {app_info['short_description']}")
            print(f"Rating Count: {app_info['rating_count']}")
            print(f"Rating Stars: {app_info['rating_stars']}")
            print(f"Current Version: {app_info['current_version']}")
            print(f"Check Date: {app_info['check_date']}")
        print("-" * 40)
  • iOS App Store Rating Checker Python Script

    This Python script allows users to input an iOS app name and retrieves its overall rating and total number of ratings from the iTunes Search API. It also displays the current date and time when the data was checked, providing a simple way to monitor app performance on the App Store.

    Click to view script…
    import requests
    from datetime import datetime
    
    # Get the app name from the user
    app_name = input("Enter the app name: ")
    
    # Base URL for the iTunes Search API
    base_url = "https://itunes.apple.com/search"
    
    # Parameters for the API request
    params = {
        "term": app_name,
        "country": "us",
        "media": "software"
    }
    
    try:
        # Send GET request to the API
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # Raise an exception for HTTP errors
    
        # Parse the JSON response
        data = response.json()
    
        # Check if any apps were found
        if data["resultCount"] > 0:
            # Extract the first app's data
            app = data["results"][0]
            rating = app.get("averageUserRating", "N/A")
            if rating != "N/A":
                rating = f"{rating:.1f}"  # Format rating to one decimal place
            count = app.get("userRatingCount", "N/A")
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
            # Print the results
            print(f"App Name: {app['trackName']}")
            print(f"Overall Rating: {rating}")
            print(f"Total Ratings: {count}")
            print(f"Date Checked: {current_time}")
        else:
            print("No apps found with that name.")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
  • iTunes TV Show Seasons Release Finder Swift Script

    This Swift script lets you search for a TV show by title from the macOS Terminal, displaying its initial release date and a chronological list of seasons with their release dates, all pulled from the iTunes Store API. Perfect for TV enthusiasts wanting quick access to show timelines!

    Click to view script…
    #!/usr/bin/env swift
    
    import Foundation
    
    // Define structs to match the iTunes Search API response for TV seasons
    struct SearchResponse: Codable {
        let resultCount: Int
        let results: [TVSeason]
    }
    
    struct TVSeason: Codable {
        let artistName: String      // The TV show's name
        let collectionName: String  // The season's name
        let releaseDate: Date       // The season's release date
    }
    
    // Check for command-line arguments
    if CommandLine.arguments.count < 2 {
        print("Usage: \(CommandLine.arguments[0]) <tv show title>")
        exit(1)
    }
    
    // Combine all arguments after the script name into a single TV show title
    let tvShowTitle = CommandLine.arguments[1...].joined(separator: " ")
    
    // Construct the API URL for searching TV seasons
    let baseURL = "https://itunes.apple.com/search"
    let queryItems = [
        URLQueryItem(name: "term", value: tvShowTitle),
        URLQueryItem(name: "media", value: "tvShow"),
        URLQueryItem(name: "entity", value: "tvSeason"),
        URLQueryItem(name: "country", value: "us")
    ]
    var urlComponents = URLComponents(string: baseURL)!
    urlComponents.queryItems = queryItems
    guard let url = urlComponents.url else {
        print("Invalid URL.")
        exit(1)
    }
    
    // Set up semaphore to handle asynchronous URLSession task
    let semaphore = DispatchSemaphore(value: 0)
    var exitCode: Int32 = 0  // Exit code for the script
    
    // Perform the network request
    let session = URLSession.shared
    let task = session.dataTask(with: url) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            exitCode = 1
        } else if let data = data {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601 // Handle ISO 8601 date format
            do {
                let searchResponse = try decoder.decode(SearchResponse.self, from: data)
                if searchResponse.resultCount > 0 {
                    let seasons = searchResponse.results
                    let showName = seasons[0].artistName
                    // Sort seasons by release date
                    let sortedSeasons = seasons.sorted { $0.releaseDate < $1.releaseDate }
                    // Display show info and initial release date
                    if let firstReleaseDate = sortedSeasons.first?.releaseDate {
                        let dateFormatter = DateFormatter()
                        dateFormatter.dateStyle = .long
                        let formattedDate = dateFormatter.string(from: firstReleaseDate)
                        print("TV Show: \(showName)")
                        print("Initial Release Date: \(formattedDate)")
                    } else {
                        print("TV Show: \(showName)")
                        print("Release date not available.")
                    }
                    // List all seasons
                    print("Seasons:")
                    for season in sortedSeasons {
                        let seasonDateFormatter = DateFormatter()
                        seasonDateFormatter.dateStyle = .long
                        let seasonFormattedDate = seasonDateFormatter.string(from: season.releaseDate)
                        print("- \(season.collectionName): \(seasonFormattedDate)")
                    }
                    exitCode = 0
                } else {
                    print("No TV show found for \"\(tvShowTitle)\".")
                    exitCode = 1
                }
            } catch {
                print("Error decoding JSON: \(error)")
                exitCode = 1
            }
        } else {
            print("No data received.")
            exitCode = 1
        }
        semaphore.signal() // Signal completion
    }
    
    // Start the task and wait for it to complete
    task.resume()
    semaphore.wait()
    exit(exitCode)

  • iTunes Movie Release Lookup Swift Script

    This Swift script searches the iTunes Store for a movie by title, provided as a command-line argument, and prints the release date of the first matching result. It uses the iTunes Search API and handles errors gracefully with appropriate exit codes

    Click to view script…
    #!/usr/bin/env swift
    
    import Foundation
    
    // Define structs to match the iTunes Search API response
    struct SearchResponse: Codable {
        let resultCount: Int
        let results: [Movie]
    }
    
    struct Movie: Codable {
        let trackName: String
        let releaseDate: Date
    }
    
    // Check for command-line arguments
    if CommandLine.arguments.count < 2 {
        print("Usage: \(CommandLine.arguments[0]) <movie title>")
        exit(1)
    }
    
    // Combine all arguments after the script name into a single movie title
    let movieTitle = CommandLine.arguments[1...].joined(separator: " ")
    
    // Construct the API URL
    let baseURL = "https://itunes.apple.com/search"
    let queryItems = [
        URLQueryItem(name: "term", value: movieTitle),
        URLQueryItem(name: "media", value: "movie"),
        URLQueryItem(name: "entity", value: "movie")
    ]
    var urlComponents = URLComponents(string: baseURL)!
    urlComponents.queryItems = queryItems
    guard let url = urlComponents.url else {
        print("Invalid URL.")
        exit(1)
    }
    
    // Set up semaphore to handle asynchronous URLSession task
    let semaphore = DispatchSemaphore(value: 0)
    var exitCode: Int32 = 0  // Explicitly typed as Int32 to match exit() requirement
    
    // Perform the network request
    let session = URLSession.shared
    let task = session.dataTask(with: url) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            exitCode = 1
        } else if let data = data {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601 // Handle ISO 8601 date format from API
            do {
                let searchResponse = try decoder.decode(SearchResponse.self, from: data)
                if searchResponse.resultCount > 0 {
                    let movie = searchResponse.results[0] // Take the first result
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateStyle = .long
                    let formattedDate = dateFormatter.string(from: movie.releaseDate)
                    print("Release date of \(movie.trackName): \(formattedDate)")
                    exitCode = 0
                } else {
                    print("No results found for \"\(movieTitle)\".")
                    exitCode = 1
                }
            } catch {
                print("Error decoding JSON: \(error)")
                exitCode = 1
            }
        } else {
            print("No data received.")
            exitCode = 1
        }
        semaphore.signal() // Signal completion of the network task
    }
    
    // Start the task and wait for it to complete
    task.resume()
    semaphore.wait()
    exit(exitCode)