├── .gitattributes ├── assets ├── icon.ico └── icon.png ├── requirements.txt ├── SECURITY.md ├── .github ├── FUNDING.yml └── ISSUE_TEMPLATE │ └── bug_report.md ├── CONTRIBUTING.md ├── apple.py ├── README.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── search.py ├── LICENSE ├── main-mac.py └── main.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /assets/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shouryashashank/Trackster/HEAD/assets/icon.ico -------------------------------------------------------------------------------- /assets/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shouryashashank/Trackster/HEAD/assets/icon.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | flet 2 | moviepy 3 | mutagen 4 | requests 5 | spotipy 6 | tqdm 7 | python-dotenv 8 | yt-dlp 9 | rich 10 | yarl 11 | beautifulsoup4 12 | ssl 13 | pyDes 14 | pytube-cypher-fix==15.0.2 15 | 16 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Use this section to tell people about which versions of your project are 6 | currently being supported with security updates. 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | 5.1.x | :white_check_mark: | 11 | | 5.0.x | :x: | 12 | | 4.0.x | :white_check_mark: | 13 | | < 4.0 | :x: | 14 | 15 | ## Reporting a Vulnerability 16 | 17 | Use this section to tell people how to report a vulnerability. 18 | 19 | Tell them where to go, how often they can expect to get an update on a 20 | reported vulnerability, what to expect if the vulnerability is accepted or 21 | declined, etc. 22 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [shouryashashank] 4 | patreon: Predacons 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: pypi/predacons 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 12 | polar: # Replace with a single Polar username 13 | buy_me_a_coffee: # Replace with a single Buy Me a Coffee username 14 | custom: [predacons@ybl,https://pay.upilink.in/pay/predacons@ybl] 15 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Trackster Flet App 2 | 3 | Thank you for considering contributing to the Trackster Flet App! Here are some guidelines to help you get started. 4 | 5 | ## How to Contribute 6 | 7 | 1. **Fork the repository**: Click the "Fork" button at the top right of the repository page. 8 | 9 | 2. **Clone your fork**: 10 | ```sh 11 | git clone https://github.com/shouryashashank/Trackster.git 12 | ``` 13 | 14 | 3. **Create a new branch**: 15 | ```sh 16 | git checkout -b feature-name 17 | ``` 18 | 19 | 4. **Make your changes**: Implement your feature or fix the bug. 20 | 21 | 5. **Commit your changes**: 22 | ```sh 23 | git add . 24 | git commit -m "Description of your changes" 25 | ``` 26 | 27 | 6. **Push to your branch**: 28 | ```sh 29 | git push origin feature-name 30 | ``` 31 | 32 | 7. **Create a Pull Request**: Go to the repository on GitHub and click the "New Pull Request" button. 33 | 34 | ## Code Style 35 | 36 | - Follow the existing code style. 37 | - Write clear and concise commit messages. 38 | 39 | ## Reporting Issues 40 | 41 | If you find a bug or have a feature request, please create an issue on GitHub. 42 | 43 | ## Additional Notes 44 | 45 | - Ensure your code passes all tests before submitting a pull request. 46 | - Be respectful and considerate in your interactions with others. 47 | 48 | Thank you for your contributions! 49 | -------------------------------------------------------------------------------- /apple.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | import re 4 | import tqdm 5 | 6 | def get_song_details(link): 7 | try: 8 | response = requests.get(link) 9 | response.raise_for_status() 10 | html = response.text 11 | soup = BeautifulSoup(html, "html.parser") 12 | title = soup.find('meta', attrs = {"property":"og:title"}) 13 | if title: 14 | content = title.get('content') 15 | content = content.replace("on AppleÂ\xa0Music", "audio") 16 | return content 17 | else: 18 | print("No meta tag found") 19 | return None 20 | except requests.RequestException as e: 21 | print(f"Request error: {e}") 22 | return None 23 | except Exception as e: 24 | print(f"An error occurred: {e}") 25 | return None 26 | 27 | def get_playlist(url): 28 | try: 29 | response = requests.get(url) 30 | response.raise_for_status() 31 | html = response.text 32 | soup = BeautifulSoup(html, 'html.parser') 33 | 34 | applelinks = soup.find_all('meta', attrs={"property": "music:song"}) 35 | song_list = [] 36 | for link in tqdm.tqdm(enumerate(applelinks), total=len(applelinks), desc="Processing songs"): 37 | link_str = str(link[1]) 38 | match = re.search(r'content="(https?://[^"]+)"', link_str) 39 | if match: 40 | url = match.group(1) 41 | song_search_term = get_song_details(url) 42 | song_list.append(song_search_term) 43 | return song_list 44 | except requests.RequestException as e: 45 | print(f"Request error: {e}") 46 | except Exception as e: 47 | print(f"An error occurred: {e}") 48 | return [] 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🎵 Trackster 🎵 2 | 3 | Welcome to **Trackster**! Trackster is a funky Flet app that allows you to download playlists from Spotify, Apple Music and YouTube. 🎧✨ 4 | 5 | ## Features 6 | - 📥 Download entire playlists from YouTube, Apple Music and Spotify. 7 | - 🎨 User-friendly interface with a cool progress bar. 8 | - 🖼️ Automatically adds metadata and album art to your downloaded tracks. 9 | - 🔍 Search for tracks on Spotify and YouTube. 10 | - 🛠️ Customizable settings for file handling. 11 | - 🎚️ 320kbps hi-res music download 12 | 13 | 14 | 15 | ## How to Run the App 16 | 17 | ### Option 1: Run from Source 18 | 1. Clone the repository: 19 | ```sh 20 | git clone https://github.com/shouryashashank/Trackster.git 21 | cd Trackster 22 | ``` 23 | 24 | 2. Install the required dependencies: 25 | ```sh 26 | pip install -r requirements.txt 27 | ``` 28 | 29 | 3. Run the app: 30 | ```sh 31 | flet run main.py 32 | ``` 33 | 34 | ### Option 2: Download Executable 35 | 1. Go to the [Releases](https://github.com/shouryashashank/Trackster/releases) page. 36 | 2. Download the latest executable file for your operating system. 37 | 3. Run the downloaded executable file to start the app. 38 | 39 | ## Additional requirements 40 | * ffmpeg is now required for the mp3 conversion 41 | 42 | ## Supported Platforms 43 | - Currently supported: **Windows**, **Linux**, **Mac** 44 | - Coming soon: **Android** 45 | 46 | **Help Needed**: If you can help compile Trackster for iOS, please reach out or contribute to the project. Your assistance would be greatly appreciated! 47 | 48 | ## Usage 49 | 1. **Select Output Directory**: Choose the folder where you want to save your downloaded music. 50 | 2. **Enter Playlist URL**: Input the URL of the YouTube or Spotify playlist you want to download. 51 | 3. **Choose File Handling Option**: Decide what to do if a file already exists (Replace all, Skip all). 52 | 4. **Download**: Click the "Download Playlist" button and let Trackster do the magic! 🎩✨ 53 | 54 | ### Adding Spotify API Keys 55 | You can add your Spotify API keys through the app's settings: 56 | 1. Click on the hamburger menu in the top right corner. 57 | 2. Enter your Spotify Client ID and Client Secret in the provided fields. 58 | 3. Click "Save" to update the settings. 59 | 60 | ## Limitations 61 | - **No Proper Continue Option**: You can pause and resume downloads by restarting the app, but it takes some time to re-initiate and could be improved. 62 | 63 | ## Disclaimer 64 | **Support the Artists** : This tool is intended for personal use only. Please support the artists by purchasing their music or streaming it through official channels. 💖🎶 65 | - make sure to buy the content you are downloaing 66 | - if you use this software obtained from any source it is preasumed that you own the content you are downloading 67 | --- 68 | 69 | Enjoy your music with Trackster! 🎉🎵 70 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 105 | __pypackages__/ 106 | 107 | # Celery stuff 108 | celerybeat-schedule 109 | celerybeat.pid 110 | 111 | # SageMath parsed files 112 | *.sage.py 113 | 114 | # Environments 115 | .env 116 | .venv 117 | env/ 118 | venv/ 119 | ENV/ 120 | env.bak/ 121 | venv.bak/ 122 | 123 | # Spyder project settings 124 | .spyderproject 125 | .spyproject 126 | 127 | # Rope project settings 128 | .ropeproject 129 | 130 | # mkdocs documentation 131 | /site 132 | 133 | # mypy 134 | .mypy_cache/ 135 | .dmypy.json 136 | dmypy.json 137 | 138 | # Pyre type checker 139 | .pyre/ 140 | 141 | # pytype static type analyzer 142 | .pytype/ 143 | 144 | # Cython debug symbols 145 | cython_debug/ 146 | 147 | # PyCharm 148 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 149 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 150 | # and can be added to the global gitignore or merged into this file. For a more nuclear 151 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 152 | #.idea/ 153 | failed_downloads.txt 154 | /music-yt 155 | assets/youtube-svgrepo-com.svgZone.Identifier 156 | synced_updated.txt 157 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | . 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /search.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import base64 3 | from pyDes import * 4 | import os 5 | import urllib.request 6 | import time 7 | from moviepy.editor import AudioFileClip 8 | from mutagen.id3 import ID3, TIT2, TPE1, TPE2, TALB, TDRC, TRCK, TSRC, USLT, APIC 9 | import asyncio 10 | import aiohttp 11 | from aiohttp import ClientTimeout 12 | 13 | class Song: 14 | """Represents a single song and its metadata extracted from the API JSON. 15 | 16 | Initialize with the raw song JSON (dictionary) and access common fields as 17 | attributes. Use to_dict() to get a serializable representation. 18 | """ 19 | def __init__(self, song_json: dict): 20 | self.raw = song_json or {} 21 | # common top-level fields 22 | self.id = self.raw.get('id') 23 | self.title = self.raw.get('title') 24 | self.subtitle = self.raw.get('subtitle') 25 | self.type = self.raw.get('type') 26 | self.perma_url = self.raw.get('perma_url') 27 | self.image = self.raw.get('image') 28 | self.language = self.raw.get('language') 29 | self.year = self.raw.get('year') 30 | self.play_count = self.raw.get('play_count') 31 | self.explicit_content = self.raw.get('explicit_content') 32 | self.list_count = self.raw.get('list_count') 33 | self.more_info = self.raw.get('more_info', {}) 34 | 35 | # more_info nested fields (safely extracted) 36 | self.album_id = self.more_info.get('album_id') 37 | self.album = self.more_info.get('album') 38 | self.duration = self.more_info.get('duration') 39 | self.encrypted_media_url = self.more_info.get('encrypted_media_url') 40 | self.decrypted_media_url = self.decrypt_url(self.encrypted_media_url) if self.encrypted_media_url else None 41 | self.vlink = self.more_info.get('vlink') 42 | self.artistMap = self.more_info.get('artistMap', {}) 43 | 44 | 45 | def decrypt_url(self,url): 46 | des_cipher = des(b"38346591", ECB, b"\0\0\0\0\0\0\0\0", 47 | pad=None, padmode=PAD_PKCS5) 48 | enc_url = base64.b64decode(url.strip()) 49 | dec_url = des_cipher.decrypt(enc_url, padmode=PAD_PKCS5).decode('utf-8') 50 | dec_url = dec_url.replace("_96.mp4", "_320.mp4") 51 | return dec_url 52 | 53 | def to_dict(self): 54 | """Return a JSON-serializable dict of song metadata.""" 55 | return { 56 | 'id': self.id, 57 | 'title': self.title, 58 | 'subtitle': self.subtitle, 59 | 'type': self.type, 60 | 'perma_url': self.perma_url, 61 | 'image': self.image, 62 | 'language': self.language, 63 | 'year': self.year, 64 | 'play_count': self.play_count, 65 | 'explicit_content': self.explicit_content, 66 | 'list_count': self.list_count, 67 | 'more_info': self.more_info, 68 | } 69 | 70 | def __repr__(self): 71 | return f"" 72 | 73 | class Search: 74 | def __init__(self): 75 | self.search_url ="https://www.jiosaavn.com/api.php?__call=autocomplete.get&_format=json&_marker=0&cc=in&includeMetaTags=1&query=" 76 | 77 | pass 78 | 79 | def search(self, query): 80 | # Return a structured set of candidates: topresult, artists (list), albums (list) 81 | print(f"Searching for: {query}") 82 | search_url = self.search_url + query 83 | try: 84 | response = requests.get(search_url, timeout=10) 85 | except Exception as e: 86 | print(f"Error fetching search results: {e}") 87 | return None 88 | 89 | if response.status_code != 200: 90 | print("Error fetching search results") 91 | return None 92 | 93 | try: 94 | data = response.json() 95 | except Exception: 96 | return None 97 | 98 | topresult = None 99 | artists = [] 100 | albums = [] 101 | 102 | # preferred: topquery.data 103 | top_query_data = data.get('topquery', {}).get('data', []) 104 | if isinstance(top_query_data, list) and top_query_data: 105 | topresult = top_query_data[0] 106 | # also collect artists/albums from topquery 107 | for item in top_query_data: 108 | if item.get('type') == 'artist' and len(artists) < 3: 109 | artists.append(item) 110 | elif item.get('type') == 'album' and len(albums) < 3: 111 | albums.append(item) 112 | 113 | # fallback: scan full response for items 114 | def scan(obj,topresult_ref): 115 | if isinstance(obj, dict): 116 | for v in obj.values(): 117 | scan(v,topresult_ref) 118 | elif isinstance(obj, list): 119 | for elem in obj: 120 | if isinstance(elem, dict): 121 | t = elem.get('type') 122 | if t == 'artist' and len(artists) < 3: 123 | artists.append(elem) 124 | elif t == 'album' and len(albums) < 3: 125 | albums.append(elem) 126 | # capture topresult if still none 127 | if topresult_ref is None and elem.get('type') in ('artist', 'album', 'song'): 128 | topresult_ref = elem 129 | # stop early if all collected 130 | if len(artists) >= 3 and len(albums) >= 3 and topresult_ref is not None: 131 | return 132 | scan(elem,topresult_ref) 133 | # run scan 134 | scan(data,topresult) 135 | 136 | # ensure uniqueness 137 | def uniq(lst): 138 | seen = set() 139 | out = [] 140 | for it in lst: 141 | id_ = it.get('id') or it.get('perma_url') or repr(it) 142 | if id_ not in seen: 143 | seen.add(id_) 144 | out.append(it) 145 | return out 146 | 147 | artists = uniq(artists)[:3] 148 | albums = uniq(albums)[:3] 149 | 150 | result = { 151 | 'topresult': topresult, 152 | 'artists': artists, 153 | 'albums': albums, 154 | } 155 | 156 | # if nothing meaningful found, return "not found" to keep compatibility 157 | if not topresult and not artists and not albums: 158 | return "not found" 159 | 160 | return result 161 | 162 | def get_songs_from_artist(self, artist_json): 163 | artist_id = artist_json.get('id') 164 | if not artist_id: 165 | return "Artist ID not found" 166 | perma = artist_json.get('url') 167 | if not perma: 168 | return [] 169 | token = perma.rstrip('/').split('/')[-1] 170 | if not token: 171 | return [] 172 | songs_list = [] 173 | page = 0 174 | base = ('https://www.jiosaavn.com/api.php?__call=webapi.get&token={token}' 175 | '&type=artist&n_song=50&n_album=50&sub_type=&category=latest' 176 | '&sort_order=desc&includeMetaTags=0&ctx=web6dot0&api_version=4' 177 | '&_format=json&_marker=0') 178 | while True: 179 | url = base.format(token=token) + f'&p={page}' 180 | print(f"Fetching songs from URL: {url}") 181 | try: 182 | resp = requests.get(url, timeout=15) 183 | except Exception: 184 | break 185 | if resp.status_code != 200: 186 | break 187 | try: 188 | data = resp.json() 189 | except Exception: 190 | break 191 | 192 | candidates = [] 193 | for key in ('topSongs', 'songs', 'data', 'songs_list'): 194 | v = data.get(key) 195 | if isinstance(v, list) and v: 196 | candidates = v 197 | break 198 | 199 | if not candidates: 200 | for v in data.values(): 201 | if isinstance(v, list) and v and isinstance(v[0], dict) and v[0].get('type') == 'song': 202 | candidates = v 203 | break 204 | 205 | if not candidates: 206 | break 207 | 208 | for s in candidates: 209 | try: 210 | songs_list.append(Song(s)) 211 | except Exception as e: 212 | print(f"Error parsing song data, skipping... {e}") 213 | continue 214 | 215 | page += 1 216 | 217 | return songs_list 218 | 219 | def get_songs_from_album(self, album_json): 220 | """Fetch songs for an album JSON (same shape as the example). 221 | 222 | Extracts token from album 'url' (perma), calls the album API and returns 223 | a list of Song instances for each track in the album's 'list'. 224 | """ 225 | perma = album_json.get('url') or album_json.get('perma_url') 226 | if not perma: 227 | return [] 228 | token = perma.rstrip('/').split('/')[-1] 229 | if not token: 230 | return [] 231 | 232 | url = (f'https://www.jiosaavn.com/api.php?__call=webapi.get&token={token}' 233 | '&type=album&includeMetaTags=0&ctx=web6dot0&api_version=4' 234 | '&_format=json&_marker=0') 235 | print(f"Fetching album data from URL: {url}") 236 | try: 237 | resp = requests.get(url, timeout=15) 238 | except Exception: 239 | return [] 240 | if resp.status_code != 200: 241 | return [] 242 | try: 243 | data = resp.json() 244 | except Exception: 245 | return [] 246 | 247 | # album songs are usually under 'list' 248 | candidates = data.get('list') or data.get('songs') or data.get('data') or [] 249 | songs_list = [] 250 | if isinstance(candidates, list): 251 | for s in candidates: 252 | try: 253 | songs_list.append(Song(s)) 254 | except Exception as e: 255 | print(f"Error parsing album song, skipping... {e}") 256 | continue 257 | else: 258 | # if 'list' is a dict containing 'list' key etc. 259 | for v in data.values(): 260 | if isinstance(v, list) and v and isinstance(v[0], dict) and v[0].get('type') == 'song': 261 | for s in v: 262 | try: 263 | songs_list.append(Song(s)) 264 | except Exception as e: 265 | print(f"Error parsing album song, skipping... {e}") 266 | continue 267 | break 268 | 269 | return songs_list 270 | 271 | class DownloadSong: 272 | def __init__(self, song, output_folder="music-yt", skip=False): 273 | self.song = song 274 | self.output_folder = output_folder if output_folder.endswith(os.sep) else output_folder + os.sep 275 | self.skip = bool(skip) 276 | 277 | def download_song(self) -> str: 278 | """Download the song using decrypted_media_url, convert to mp3, and add metadata and album art. 279 | 280 | Returns the path to the final mp3 file on success, or raises an exception on failure. 281 | """ 282 | if not self.song or not getattr(self.song, 'decrypted_media_url', None): 283 | raise ValueError("Song has no decrypted URL") 284 | 285 | # prepare folders 286 | tmp_dir = os.path.join(self.output_folder, 'tmp') 287 | os.makedirs(tmp_dir, exist_ok=True) 288 | os.makedirs(self.output_folder, exist_ok=True) 289 | 290 | # sanitize filename 291 | title = self.song.title or "unknown" 292 | safe_title = "".join(c for c in title if c not in ['/', '\\', '|', '?', '*', ':', '>', '<', '"']) 293 | 294 | video_file = os.path.join(tmp_dir, f"{safe_title}.mp4") 295 | audio_file = os.path.join(tmp_dir, f"{safe_title}.mp3") 296 | final_file = os.path.join(self.output_folder, f"{safe_title}.mp3") 297 | 298 | # If skip flag is True and final file exists, skip downloading 299 | if self.skip and os.path.exists(final_file): 300 | print(f"Skipping existing file: {final_file}") 301 | return final_file 302 | 303 | url = self.song.decrypted_media_url 304 | # retry parameters 305 | max_attempts = 3 306 | backoff = 1 307 | 308 | # download the media with retries 309 | for attempt in range(1, max_attempts + 1): 310 | try: 311 | resp = requests.get(url, stream=True, timeout=30) 312 | resp.raise_for_status() 313 | with open(video_file, 'wb') as f: 314 | for chunk in resp.iter_content(chunk_size=8192): 315 | if chunk: 316 | f.write(chunk) 317 | break 318 | except Exception as e: 319 | print(f"Attempt {attempt} - failed to download {title} from {url}: {e}") 320 | if attempt == max_attempts: 321 | raise 322 | time.sleep(backoff) 323 | backoff *= 2 324 | 325 | # convert to mp3 (high quality similar to main.py) with retry 326 | for attempt in range(1, max_attempts + 1): 327 | try: 328 | clip = AudioFileClip(video_file) 329 | try: 330 | clip.write_audiofile(audio_file, bitrate="3000k") 331 | finally: 332 | clip.close() 333 | break 334 | except Exception as e: 335 | print(f"Attempt {attempt} - failed to convert {video_file} to mp3: {e}") 336 | if attempt == max_attempts: 337 | # cleanup and re-raise 338 | try: 339 | os.remove(video_file) 340 | except Exception: 341 | pass 342 | raise 343 | time.sleep(backoff) 344 | backoff *= 2 345 | 346 | # remove downloaded mp4 347 | try: 348 | os.remove(video_file) 349 | except Exception: 350 | pass 351 | 352 | # add metadata using mutagen with retries 353 | for attempt in range(1, max_attempts + 1): 354 | try: 355 | tags = ID3() 356 | # artist 357 | artist_name = getattr(self.song, 'subtitle', None) or getattr(self.song, 'artistMap', None) or '' 358 | if isinstance(artist_name, dict): 359 | # if artistMap present, join names 360 | artist_name = ', '.join(v.get('name', '') for v in artist_name.values()) 361 | tags['TPE1'] = TPE1(encoding=3, text=artist_name or '') 362 | # album (use album or album_id) 363 | tags['TALB'] = TALB(encoding=3, text=getattr(self.song, 'album', '') or '') 364 | tags['TIT2'] = TIT2(encoding=3, text=title) 365 | # release year if available 366 | if getattr(self.song, 'year', None): 367 | tags['TDRC'] = TDRC(encoding=3, text=str(self.song.year)) 368 | # track number not available here; leave blank 369 | tags.save(audio_file) 370 | 371 | # add album art if image available 372 | if getattr(self.song, 'image', None): 373 | with urllib.request.urlopen(self.song.image) as img: 374 | img_data = img.read() 375 | audio = ID3(audio_file) 376 | audio['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=img_data) 377 | audio.save(v2_version=3) 378 | break 379 | except Exception as e: 380 | print(f"Attempt {attempt} - failed to set metadata for {title}: {e}") 381 | if attempt == max_attempts: 382 | print(f"Giving up on tagging for {title}") 383 | else: 384 | time.sleep(backoff) 385 | backoff *= 2 386 | 387 | # move final file to output folder 388 | try: 389 | if os.path.exists(final_file): 390 | os.remove(final_file) 391 | os.replace(audio_file, final_file) 392 | except Exception as e: 393 | # fallback to copy 394 | import shutil 395 | try: 396 | shutil.copy2(audio_file, final_file) 397 | os.remove(audio_file) 398 | except Exception as e2: 399 | print(f"Failed to move/copy final file for {title}: {e} / {e2}") 400 | raise 401 | 402 | return final_file 403 | 404 | async def download_song_async(self, session: aiohttp.ClientSession, semaphore: asyncio.Semaphore) -> str: 405 | """Async version: download, convert, tag and return final path.""" 406 | if not self.song or not getattr(self.song, 'decrypted_media_url', None): 407 | raise ValueError("Song has no decrypted URL") 408 | 409 | # prepare file names early to allow skip check before acquiring semaphore 410 | title = self.song.title or "unknown" 411 | safe_title = "".join(c for c in title if c not in ['/', '\\', '|', '?', '*', ':', '>', '<', '"']) 412 | final_file = os.path.join(self.output_folder, f"{safe_title}.mp3") 413 | 414 | # If skip flag is True and final file exists, skip downloading 415 | if self.skip and os.path.exists(final_file): 416 | print(f"Skipping existing file: {final_file}") 417 | return final_file 418 | 419 | async with semaphore: 420 | # prepare folders 421 | tmp_dir = os.path.join(self.output_folder, 'tmp') 422 | os.makedirs(tmp_dir, exist_ok=True) 423 | os.makedirs(self.output_folder, exist_ok=True) 424 | 425 | video_file = os.path.join(tmp_dir, f"{safe_title}.mp4") 426 | audio_file = os.path.join(tmp_dir, f"{safe_title}.mp3") 427 | 428 | url = self.song.decrypted_media_url 429 | timeout = ClientTimeout(total=60) 430 | 431 | # async download with retries 432 | max_attempts = 3 433 | backoff = 1 434 | for attempt in range(1, max_attempts + 1): 435 | try: 436 | async with session.get(url, timeout=timeout) as resp: 437 | resp.raise_for_status() 438 | with open(video_file, 'wb') as f: 439 | async for chunk in resp.content.iter_chunked(8192): 440 | f.write(chunk) 441 | break 442 | except Exception as e: 443 | print(f"Attempt {attempt} - failed to download (async) {title} from {url}: {e}") 444 | if attempt == max_attempts: 445 | raise 446 | await asyncio.sleep(backoff) 447 | backoff *= 2 448 | 449 | # convert to mp3 using moviepy (blocking) - run in threadpool 450 | loop = asyncio.get_running_loop() 451 | def convert(): 452 | clip = AudioFileClip(video_file) 453 | try: 454 | clip.write_audiofile(audio_file, bitrate="3000k") 455 | finally: 456 | clip.close() 457 | try: 458 | os.remove(video_file) 459 | except Exception: 460 | pass 461 | 462 | # run conversion with retries in executor 463 | for attempt in range(1, max_attempts + 1): 464 | try: 465 | await loop.run_in_executor(None, convert) 466 | break 467 | except Exception as e: 468 | print(f"Attempt {attempt} - failed to convert (async) {video_file}: {e}") 469 | if attempt == max_attempts: 470 | raise 471 | await asyncio.sleep(backoff) 472 | backoff *= 2 473 | 474 | # tagging (blocking) - run in threadpool with retries 475 | def tag(): 476 | try: 477 | tags = ID3() 478 | artist_name = getattr(self.song, 'subtitle', None) or getattr(self.song, 'artistMap', None) or '' 479 | if isinstance(artist_name, dict): 480 | artist_name = ', '.join(v.get('name', '') for v in artist_name.values()) 481 | tags['TPE1'] = TPE1(encoding=3, text=artist_name or '') 482 | tags['TALB'] = TALB(encoding=3, text=getattr(self.song, 'album', '') or '') 483 | tags['TIT2'] = TIT2(encoding=3, text=title) 484 | if getattr(self.song, 'year', None): 485 | tags['TDRC'] = TDRC(encoding=3, text=str(self.song.year)) 486 | tags.save(audio_file) 487 | 488 | if getattr(self.song, 'image', None): 489 | with urllib.request.urlopen(self.song.image) as img: 490 | img_data = img.read() 491 | audio = ID3(audio_file) 492 | audio['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=img_data) 493 | audio.save(v2_version=3) 494 | except Exception as e: 495 | raise 496 | 497 | for attempt in range(1, max_attempts + 1): 498 | try: 499 | await loop.run_in_executor(None, tag) 500 | break 501 | except Exception as e: 502 | print(f"Attempt {attempt} - failed to tag (async) {title}: {e}") 503 | if attempt == max_attempts: 504 | print(f"Giving up on tagging for {title} (async)") 505 | else: 506 | await asyncio.sleep(backoff) 507 | backoff *= 2 508 | 509 | # move file 510 | try: 511 | if os.path.exists(final_file): 512 | os.remove(final_file) 513 | os.replace(audio_file, final_file) 514 | except Exception as e: 515 | import shutil 516 | try: 517 | shutil.copy2(audio_file, final_file) 518 | os.remove(audio_file) 519 | except Exception as e2: 520 | print(f"Failed to move/copy final file for {title} (async): {e} / {e2}") 521 | raise 522 | 523 | return final_file 524 | 525 | def main(): 526 | search_instance = Search() 527 | query = "From zero" 528 | result = search_instance.search(query) 529 | print(result) 530 | if result: 531 | if result.get('type') == 'artist': 532 | print("Fetching songs for artist...") 533 | songs = search_instance.get_songs_from_artist(result) 534 | for song in songs: 535 | print(song.to_dict()) 536 | elif result.get('type') == 'album': 537 | print("Fetching songs for album...") 538 | songs = search_instance.get_songs_from_album(result) 539 | # run downloads in parallel using asyncio and aiohttp 540 | async def run_all(): 541 | sem = asyncio.Semaphore(4) # limit concurrency 542 | timeout = ClientTimeout(total=120) 543 | async with aiohttp.ClientSession(timeout=timeout) as session: 544 | tasks = [DownloadSong(song).download_song_async(session, sem) for song in songs] 545 | for fut in asyncio.as_completed(tasks): 546 | try: 547 | path = await fut 548 | print(f"Downloaded: {path}") 549 | except Exception as e: 550 | print(f"Download failed: {e}") 551 | asyncio.run(run_all()) 552 | 553 | if __name__ == "__main__": 554 | main() -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /main-mac.py: -------------------------------------------------------------------------------- 1 | import flet as ft 2 | import time 3 | import os 4 | from pytube import Playlist 5 | from moviepy import * 6 | from mutagen.easyid3 import EasyID3 7 | import requests 8 | import spotipy 9 | from spotipy.oauth2 import SpotifyClientCredentials 10 | from mutagen.id3 import APIC, ID3 11 | import urllib.request 12 | from tqdm import tqdm 13 | from dotenv import load_dotenv 14 | import os 15 | import re 16 | import shutil 17 | import time 18 | import urllib.request 19 | import pickle 20 | from tqdm import tqdm 21 | import spotipy 22 | from mutagen.easyid3 import EasyID3 23 | from mutagen.id3 import APIC, ID3 24 | from pytube import YouTube 25 | import pytube.exceptions 26 | from rich.console import Console 27 | from spotipy.oauth2 import SpotifyClientCredentials 28 | from yarl import URL 29 | import ssl 30 | import sys, io 31 | from bs4 import BeautifulSoup 32 | import apple 33 | import yt_dlp 34 | from yt_dlp.utils import download_range_func 35 | import base64 36 | from pyDes import * 37 | import requests 38 | from mutagen.id3 import ID3, TIT2, TPE1, TPE2, TALB, TDRC, TRCK, TSRC, USLT, APIC 39 | from concurrent.futures import ThreadPoolExecutor 40 | import difflib 41 | 42 | 43 | 44 | # buffer = io.StringIO() 45 | # sys.stdout = sys.stderr = buffer 46 | 47 | ssl._create_default_https_context = ssl._create_unverified_context 48 | # pyinstaller --noconfirm --onefile --windowed --icon "D:\Code\github\music\Trackster\icon_for_an_app_called_trakster_used_to_download_spotify_and_youtube_playlist-removebg-preview.ico" --name "Trackster_101_Fix_Premium" "D:\Code\github\music\Trackster\main.py" 49 | file_exists_action="" 50 | failed_download = False 51 | high_quality = False 52 | search_base_url = "https://www.jiosaavn.com/api.php?__call=autocomplete.get&_format=json&_marker=0&cc=in&includeMetaTags=1&query=" 53 | song_base_url = "https://www.jiosaavn.com/api.php?__call=song.getDetails&cc=in&_marker=0%3F_marker%3D0&_format=json&pids=" 54 | lyrics_base_url = "https://www.jiosaavn.com/api.php?__call=lyrics.getLyricvideo_files&ctx=web6dot0&api_version=4&_format=json&_marker=0%3F_marker%3D0&lyrics_id=" 55 | music_folder_path = "music-yt/" # path to save the downloaded music 56 | 57 | def sanitize_filename(filename): 58 | return re.sub(r'[<>:"/\\|?*]', '', filename) 59 | 60 | def prompt_exists_action(): 61 | """ask the user what happens if the file being downloaded already exists""" 62 | global file_exists_action 63 | if file_exists_action == "SA": # SA == 'Skip All' 64 | return False 65 | elif file_exists_action == "RA": # RA == 'Replace All' 66 | return True 67 | 68 | print("This file already exists.") 69 | while True: 70 | resp = ( 71 | input("replace[R] | replace all[RA] | skip[S] | skip all[SA]: ") 72 | .upper() 73 | .strip() 74 | ) 75 | if resp in ("RA", "SA"): 76 | file_exists_action = resp 77 | if resp in ("R", "RA"): 78 | return True 79 | elif resp in ("S", "SA"): 80 | return False 81 | print("---Invalid response---") 82 | 83 | def make_alpha_numeric(string): 84 | return ''.join(char for char in string if char.isalnum()) 85 | 86 | def download_yt(yt,search_term): 87 | """download the video in mp3 format from youtube""" 88 | # remove chars that can't be in a windows file name 89 | yt.title = "".join([c for c in yt.title if c not in ['/', '\\', '|', '?', '*', ':', '>', '<', '"']]) 90 | # don't download existing files if the user wants to skip them 91 | exists = os.path.exists(f"{music_folder_path}{yt.title}.mp3") 92 | if exists and not prompt_exists_action(): 93 | return False 94 | 95 | # download the music 96 | yt_opts = { 97 | 'extract_audio': True, 98 | 'format': 'bestaudio', 99 | 'outtmpl': f"{music_folder_path}tmp/{yt.title}.mp4", 100 | } 101 | with yt_dlp.YoutubeDL(yt_opts) as ydl: 102 | ydl.download(yt.watch_url) 103 | # max_retries = 3 104 | # attempt = 0 105 | # video = None 106 | 107 | # while attempt < max_retries: 108 | # try: 109 | # video = yt.streams.filter(only_audio=True).first() 110 | # if video: 111 | # break 112 | # except Exception as e: 113 | # print(f"Attempt {attempt + 1} {search_term} failed due to: {e}") 114 | # attempt += 1 115 | # if not video: 116 | # print(f"Failed to download {search_term}") 117 | # # check if a file named failed_downloads.txt exists if not create one and append the failed download 118 | # if not os.path.exists("failed_downloads.txt"): 119 | # with open("failed_downloads.txt", "w") as f: 120 | # f.write(f"{search_term}\n") 121 | # else: 122 | # with open("failed_downloads.txt", "a") as f: 123 | # f.write(f"{search_term}\n") 124 | # return False 125 | # vid_file = video.download(output_path=f"{music_folder_path}tmp") 126 | # # convert the downloaded video to mp3 127 | # base = os.path.splitext(vid_file)[0] 128 | # audio_file = base + ".mp3" 129 | # mp4_no_frame = AudioFileClip(vid_file) 130 | # mp4_no_frame.write_audiofile(audio_file, logger=None) 131 | # mp4_no_frame.close() 132 | # os.remove(vid_file) 133 | # os.replace(audio_file, f"{music_folder_path}tmp/{yt.title}.mp3") 134 | video_file = f"{music_folder_path}tmp/{yt.title}.mp4" 135 | audio_file = f"{music_folder_path}tmp/{yt.title}.mp3" 136 | FILETOCONVERT = AudioFileClip(video_file) 137 | FILETOCONVERT.write_audiofile(audio_file) 138 | FILETOCONVERT.close() 139 | os.remove(video_file) 140 | audio_file = f"{music_folder_path}tmp/{yt.title}.mp3" 141 | return audio_file 142 | 143 | def decrypt_url(url): 144 | des_cipher = des(b"38346591", ECB, b"\0\0\0\0\0\0\0\0", 145 | pad=None, padmode=PAD_PKCS5) 146 | enc_url = base64.b64decode(url.strip()) 147 | dec_url = des_cipher.decrypt(enc_url, padmode=PAD_PKCS5).decode('utf-8') 148 | dec_url = dec_url.replace("_96.mp4", "_320.mp4") 149 | return dec_url 150 | 151 | def search_song(query): 152 | search_url = search_base_url + query 153 | response = requests.get(search_url) 154 | songs = response.json().get('songs', {}).get('data', []) 155 | if not songs: 156 | return "No songs found for the query." 157 | song_id = response.json()['songs']['data'][0]['id'] 158 | song_url = song_base_url + song_id 159 | response = requests.get(song_url) 160 | song_url = response.json()[song_id]['encrypted_media_url'] 161 | primary_artists = response.json()[song_id]['primary_artists'] 162 | album = response.json()[song_id]['album'] 163 | song = response.json()[song_id]['song'] 164 | release_date = response.json()[song_id]['release_date'] 165 | 166 | has_lyrics = response.json()[song_id]['has_lyrics'] == 'true' 167 | lyrics = "" 168 | if has_lyrics: 169 | lyrics_url = lyrics_base_url + song_id 170 | try: 171 | lyrics_response = requests.get(lyrics_url) 172 | lyrics = lyrics_response.json()['lyrics'] 173 | except Exception as e: 174 | print(f"Failed to get lyrics for {song}: {e}") 175 | 176 | return { 177 | "url": decrypt_url(song_url), 178 | "primary_artists": primary_artists, 179 | "album": album, 180 | "song": song, 181 | "release_date": release_date, 182 | "lyrics": lyrics 183 | } 184 | 185 | def download_high_quality(search_term): 186 | song = search_song(search_term) 187 | if song == "No songs found for the query.": return song 188 | song_url = song['url'] 189 | if not isinstance(song, dict): 190 | return "Unexpected response format." 191 | file = f"{music_folder_path}{os.path.basename(song['song'])}.mp3" 192 | # check if the file already exists 193 | if os.path.exists(file): 194 | if not prompt_exists_action(): 195 | return "File already exists." 196 | response = requests.get(song_url) 197 | # create new folder if it doesn't exist "tmp" 198 | if not os.path.exists(f"{music_folder_path}tmp"): 199 | os.makedirs(f"{music_folder_path}tmp") 200 | sanitized_song_name = sanitize_filename(song['song']) 201 | video_file = f"{music_folder_path}tmp/{sanitized_song_name}.mp4" 202 | audio_file = f"{music_folder_path}tmp/{sanitized_song_name}.mp3" 203 | with open(video_file, "wb") as f: 204 | f.write(response.content) 205 | FILETOCONVERT = AudioFileClip(video_file) 206 | FILETOCONVERT.write_audiofile(audio_file,bitrate="3000k") 207 | FILETOCONVERT.close() 208 | os.remove(video_file) 209 | song["mp3"] = audio_file 210 | return song 211 | # def set_metadata(metadata, file_path,lyrics): 212 | # """adds metadata to the downloaded mp3 file""" 213 | 214 | # mp3file = ID3(file_path) 215 | 216 | # # add metadata 217 | # mp3file["albumartist"] = metadata["artist_name"] 218 | # mp3file["artist"] = metadata["artists"] 219 | # mp3file["album"] = metadata["album_name"] 220 | # mp3file["title"] = metadata["track_title"] 221 | # mp3file["date"] = metadata["release_date"] 222 | # mp3file["tracknumber"] = str(metadata["track_number"]) 223 | # mp3file["isrc"] = metadata["isrc"] 224 | # if lyrics != "": 225 | # ulyrics = mp3file.getall('USLT')[0] 226 | 227 | # # change the lyrics text 228 | # ulyrics.text = lyrics 229 | # mp3file.setall('USLT', [ulyrics]) 230 | # mp3file.save() 231 | 232 | def set_metadata(metadata, file_path, lyrics): 233 | """adds metadata to the downloaded mp3 file""" 234 | 235 | mp3file = ID3(file_path) 236 | 237 | # add metadata 238 | mp3file["TPE1"] = TPE1(encoding=3, text=metadata["artist_name"]) 239 | mp3file["TPE2"] = TPE2(encoding=3, text=metadata["artists"]) 240 | mp3file["TALB"] = TALB(encoding=3, text=metadata["album_name"]) 241 | mp3file["TIT2"] = TIT2(encoding=3, text=metadata["track_title"]) 242 | mp3file["TDRC"] = TDRC(encoding=3, text=metadata["release_date"]) 243 | mp3file["TRCK"] = TRCK(encoding=3, text=str(metadata["track_number"])) 244 | mp3file["TSRC"] = TSRC(encoding=3, text=metadata["isrc"]) 245 | if lyrics != "": 246 | # Check if USLT frame exists, if not create a new one 247 | if mp3file.getall('USLT'): 248 | ulyrics = mp3file.getall('USLT')[0] 249 | ulyrics.text = lyrics 250 | else: 251 | ulyrics = USLT(encoding=3, desc='', text=lyrics) 252 | mp3file.add(ulyrics) 253 | mp3file.save() 254 | 255 | # add album cover 256 | audio = ID3(file_path) 257 | with urllib.request.urlopen(metadata["album_art"]) as albumart: 258 | audio["APIC"] = APIC( 259 | encoding=3, 260 | mime='image/jpeg', 261 | type=3, 262 | desc=u'Cover', 263 | data=albumart.read() 264 | ) 265 | audio.save() 266 | 267 | # add album cover 268 | audio = ID3(file_path) 269 | with urllib.request.urlopen(metadata["album_art"]) as albumart: 270 | audio["APIC"] = APIC( 271 | encoding=3, mime="image/jpeg", type=3, desc="Cover", data=albumart.read() 272 | ) 273 | audio.save(v2_version=3) 274 | 275 | def search_spotify(search_term : str, sp)->str: 276 | """search for the track on spotify""" 277 | search_results = sp.search(search_term, type="track", limit=1) 278 | if search_results["tracks"]["total"] == 0: 279 | return None 280 | track = search_results["tracks"]["items"][0] 281 | return track["external_urls"]["spotify"] 282 | 283 | def get_track_info_spotify(track_url,sp): 284 | res = requests.get(track_url) 285 | if res.status_code != 200: 286 | # retry 3 times 287 | for i in range(3): 288 | res = requests.get(track_url) 289 | if res.status_code == 200: 290 | break 291 | if res.status_code != 200: 292 | print("Invalid Spotify track URL") 293 | 294 | track = sp.track(track_url) 295 | 296 | track_metadata = { 297 | "artist_name": track["artists"][0]["name"], 298 | "track_title": track["name"], 299 | "track_number": track["track_number"], 300 | "isrc": track["external_ids"]["isrc"], 301 | "album_art": track["album"]["images"][1]["url"], 302 | "album_name": track["album"]["name"], 303 | "release_date": track["album"]["release_date"], 304 | "artists": [artist["name"] for artist in track["artists"]], 305 | } 306 | 307 | return track_metadata 308 | 309 | def get_track_info_youtube(video): 310 | 311 | track_metadata = { 312 | "artist_name": video.author, 313 | "track_title": video.title, 314 | "track_number": 0, 315 | "isrc": "", 316 | "album_art": video.thumbnail_url, 317 | "album_name": video.author, 318 | "release_date": video.publish_date.strftime("%Y-%m-%d"), 319 | "artists": [video.author], 320 | } 321 | 322 | return track_metadata 323 | 324 | def ensure_folder_path_ends_with_slash(folder_path): 325 | if not folder_path.endswith(os.sep): 326 | folder_path += os.sep 327 | return folder_path 328 | 329 | 330 | 331 | 332 | 333 | 334 | # Open directory dialog 335 | def get_directory_result(e: ft.FilePickerResultEvent): 336 | directory_path.value = e.path if e.path else "Cancelled!" 337 | directory_path.update() 338 | global music_folder_path 339 | music_folder_path = ensure_folder_path_ends_with_slash(e.path) 340 | print(music_folder_path) 341 | 342 | get_directory_dialog = ft.FilePicker(on_result=get_directory_result) 343 | directory_path = ft.Text() 344 | def set_theme(e,color): 345 | e.control.page.theme = ft.Theme(color_scheme_seed=color) 346 | e.control.page.update() 347 | def progress_bar(): 348 | t = ft.Text(value="") 349 | t2 = ft.Text(value = "0") 350 | pb = ft.ProgressBar(value=0) 351 | # img = "https://picsum.photos/200/200?0" 352 | def button_clicked(e): 353 | t.value = "Downloading" 354 | t.update() 355 | b.disabled = True 356 | b.update() 357 | 358 | for i in range(0, 101): 359 | # view.content.controls[0].image_src = f"https://picsum.photos/id/{i+10}/200/300" 360 | # view.content.controls[0].image_opacity = 0.2 361 | t2.value = i 362 | pb.value = i * 0.01 363 | time.sleep(0.1) 364 | view.update() 365 | t2.update() 366 | pb.update() 367 | t.value = "" 368 | t2.value = "" 369 | t.update() 370 | b.disabled = False 371 | b.update() 372 | 373 | b = ft.ElevatedButton("Download Playlist", width=200000, on_click=button_clicked) 374 | view = ft.Container( 375 | 376 | content = ft.Column( 377 | [ 378 | b, 379 | ft.Container( 380 | # image_src=img, 381 | # image_opacity= 0, 382 | # image_fit= ft.ImageFit.COVER, 383 | padding=10, 384 | content=ft.Column([ 385 | ft.Divider(opacity=0), 386 | t, 387 | pb, 388 | t2, 389 | ft.Divider(opacity=0)]), 390 | 391 | ) 392 | 393 | ],) 394 | ) 395 | return view 396 | 397 | 398 | class GestureDetector: 399 | def __init__(self): 400 | self.detector = ft.GestureDetector( 401 | on_pan_update=self.on_pan_update 402 | ) 403 | def on_pan_update(self,e): 404 | if e.delta_x<0: 405 | switch_to_sp_tab(e) 406 | elif e.delta_x>0: 407 | switch_to_yt_tab(e) 408 | def navigation_drawer(): 409 | print("hello") 410 | spotify_client_id = ft.TextField(keyboard_type=ft.KeyboardType.TEXT) 411 | spotify_client_secret = ft.TextField(keyboard_type=ft.KeyboardType.TEXT) 412 | spotify_client_id.value = os.getenv('SPOTIPY_CLIENT_ID') 413 | spotify_client_secret.value = os.getenv('SPOTIPY_CLIENT_SECRET') 414 | def save_app_settings(e): 415 | try: 416 | env_str = "SPOTIPY_CLIENT_ID=" + spotify_client_id.value + "\nSPOTIPY_CLIENT_SECRET=" + spotify_client_secret.value 417 | with open(".env", "a+") as f: 418 | f.seek(0) # Move the cursor to the beginning of the file 419 | f.truncate() # Clear the file content 420 | f.write(env_str) 421 | except Exception as e: 422 | print(e) 423 | return "app settings update failed" 424 | return "app settings updated" 425 | def yt_page_launch(e): 426 | e.control.page.launch_url('https://youtu.be/vT43uBHq974') 427 | def petreon_page_launch(e): 428 | e.control.page.launch_url('https://www.patreon.com/c/Predacons') 429 | def github_page_launch(e): 430 | e.control.page.launch_url('https://github.com/shouryashashank/Trackster') 431 | def email_page_launch(e): 432 | e.control.page.launch_url('https://www.patreon.com/messages/ffd73e51aa264a61842c446763dbaff9?mode=campaign&tab=chats') 433 | def close_end_drawer(e): 434 | e.control.page.end_drawer = end_drawer 435 | end_drawer.open = False 436 | e.control.page.update() 437 | end_drawer = ft.NavigationDrawer([ 438 | ft.SafeArea( 439 | ft.Column( 440 | [ 441 | # ft.Row( 442 | # [ 443 | # ft.Text(""), 444 | # ft.IconButton(icon=ft.icons.CLOSE,on_click=close_end_drawer) 445 | # ], 446 | # alignment=ft.MainAxisAlignment.SPACE_BETWEEN 447 | # ), 448 | # ft.Text("Spotify client id:"), 449 | # spotify_client_id, 450 | # ft.Text("Spotify client secret:"), 451 | # spotify_client_secret, 452 | # ft.ElevatedButton("Save",on_click=save_app_settings), 453 | # ft.TextButton("How To Get Spotify api api Keys",on_click=yt_page_launch), 454 | ft.TextButton("Contact support",on_click=email_page_launch), 455 | # ft.TextButton("Get version with api key already added.",on_click=petreon_page_launch), 456 | ft.TextButton("Help me buy a new phone",on_click=petreon_page_launch), 457 | ft.TextButton("See source code",on_click=github_page_launch) 458 | 459 | ] 460 | ), 461 | minimum_padding= 10, 462 | ) 463 | ]) 464 | 465 | def open_end_drawer(e): 466 | e.control.page.end_drawer = end_drawer 467 | end_drawer.open = True 468 | e.control.page.update() 469 | 470 | return open_end_drawer 471 | 472 | 473 | def popup(page,text): 474 | return ft.AlertDialog( 475 | title=ft.Text(text), 476 | on_dismiss=lambda e: page.add(ft.Text("Non-modal dialog dismissed")), 477 | ) 478 | 479 | def drop_down(): 480 | 481 | return ft.Dropdown( 482 | label="Song Exist Action", 483 | hint_text="What to do when that song already exist in your directory?", 484 | options=[ 485 | ft.dropdown.Option("Replace all"), 486 | ft.dropdown.Option("Skip all"), 487 | ], 488 | autofocus=True, 489 | ) 490 | def app_bar(): 491 | view = ft.AppBar( 492 | title=ft.Text("Trackster"), 493 | actions=[ 494 | ft.IconButton(ft.icons.MENU, style=ft.ButtonStyle(padding=0),on_click=navigation_drawer()) 495 | ], 496 | bgcolor=ft.colors.with_opacity(0.04, ft.cupertino_colors.SYSTEM_BACKGROUND), 497 | ) 498 | return view 499 | 500 | def handle_nav_change(e): 501 | if e.control.selected_index == 0: 502 | switch_to_yt_tab(e) 503 | elif e.control.selected_index == 1: 504 | switch_to_sp_tab(e) 505 | elif e.control.selected_index == 2: 506 | switch_to_am_tab(e) 507 | elif e.control.selected_index == 3: 508 | switch_to_set_tab(e) 509 | def nav_bar(): 510 | view = ft.NavigationBar( 511 | destinations=[ 512 | ft.NavigationBarDestination(icon=ft.icons.ONDEMAND_VIDEO_ROUNDED, label="Youtube"), 513 | ft.NavigationBarDestination(icon=ft.icons.MUSIC_NOTE, label="Spotify"), 514 | ft.NavigationBarDestination(icon=ft.icons.APPLE_OUTLINED, label="Apple Music"), 515 | ft.NavigationBarDestination(icon=ft.icons.SETTINGS, label="Settings") 516 | 517 | ], 518 | on_change=handle_nav_change, 519 | border=ft.Border( 520 | top=ft.BorderSide(color=ft.cupertino_colors.SYSTEM_GREY2, width=0) 521 | ), 522 | ) 523 | return view 524 | 525 | 526 | class FolderPicker(ft.Row): 527 | def build(self): 528 | view = ft.Row( 529 | [ 530 | ft.ElevatedButton( 531 | "Select Folder", 532 | icon=ft.icons.FOLDER_OPEN, 533 | on_click=lambda _: get_directory_dialog.get_directory_path() 534 | ), 535 | directory_path, 536 | # ft.Text(value="Select Output Direcotry to save the playlist", italic=False, selectable=False, style='labelSmall', ), 537 | ] 538 | ) 539 | return view 540 | def switch_to_yt_tab(e): 541 | e.control.page.title= "Youtube" 542 | set_theme(e,"Red") 543 | e.control.page.youtube_tab.visible = True 544 | e.control.page.spotify_tab.visible = False 545 | e.control.page.apple_music_tab.visible = False 546 | e.control.page.settings_tab.visible = False 547 | e.control.page.navigation_bar.selected_index = 0 548 | e.control.page.update() 549 | 550 | def switch_to_sp_tab(e): 551 | e.control.page.title= "Spotify" 552 | set_theme(e,"Green") 553 | e.control.page.youtube_tab.visible = False 554 | e.control.page.spotify_tab.visible = True 555 | e.control.page.apple_music_tab.visible = False 556 | e.control.page.settings_tab.visible = False 557 | e.control.page.navigation_bar.selected_index = 1 558 | e.control.page.update() 559 | 560 | def switch_to_am_tab(e): 561 | e.control.page.title= "Apple Music" 562 | set_theme(e,"Blue") 563 | e.control.page.youtube_tab.visible = False 564 | e.control.page.spotify_tab.visible = False 565 | e.control.page.apple_music_tab.visible = True 566 | e.control.page.settings_tab.visible = False 567 | e.control.page.navigation_bar.selected_index = 2 568 | e.control.page.update() 569 | 570 | def switch_to_set_tab(e): 571 | e.control.page.title= "Settings" 572 | set_theme(e,"Blue") 573 | e.control.page.youtube_tab.visible = False 574 | e.control.page.spotify_tab.visible = False 575 | e.control.page.apple_music_tab.visible = False 576 | e.control.page.settings_tab.visible = True 577 | e.control.page.navigation_bar.selected_index = 3 578 | e.control.page.update() 579 | def get_track_info(track_url,sp): 580 | 581 | # res = requests.get(track_url) 582 | # if res.status_code != 200: 583 | # # retry 3 times 584 | # for i in range(3): 585 | # res = requests.get(track_url) 586 | # if res.status_code == 200: 587 | # break 588 | # if res.status_code != 200: 589 | # print("Invalid Spotify track URL") 590 | try: 591 | track = sp.track(track_url) 592 | 593 | track_metadata = { 594 | "artist_name": track["artists"][0]["name"], 595 | "track_title": track["name"], 596 | "track_number": track["track_number"], 597 | "isrc": track["external_ids"]["isrc"], 598 | "album_art": track["album"]["images"][1]["url"], 599 | "album_name": track["album"]["name"], 600 | "release_date": track["album"]["release_date"], 601 | "artists": [artist["name"] for artist in track["artists"]], 602 | } 603 | except Exception as e: 604 | print("Invalid Spotify track URL") 605 | 606 | 607 | return track_metadata 608 | def find_youtube(query): 609 | query = query.replace("é", "e") 610 | query = query.replace("’", "") 611 | query = query.replace("æ", "ae") 612 | query = query.replace("ñ", "n") 613 | query = query.replace("–", "+") 614 | query = query.replace("‘", "") 615 | query = query.replace("ú", "u") 616 | 617 | 618 | phrase = query.replace(" ", "+") 619 | search_link = "https://www.youtube.com/results?search_query=" + phrase 620 | count = 0 621 | while count < 5: 622 | try: 623 | search_link = str(URL(search_link)) 624 | response = urllib.request.urlopen(search_link) 625 | break 626 | except: 627 | count += 1 628 | else: 629 | raise ValueError("Please check your internet connection and try again later.") 630 | 631 | 632 | search_results = re.findall(r"watch\?v=(\S{11})", response.read().decode()) 633 | first_vid = "https://www.youtube.com/watch?v=" + search_results[0] 634 | 635 | return first_vid 636 | 637 | def get_playlist_info(sp_playlist,sp): 638 | res = requests.get(sp_playlist) 639 | if res.status_code != 200: 640 | raise ValueError("Invalid Spotify playlist URL") 641 | pl = sp.playlist(sp_playlist) 642 | if not pl["public"]: 643 | raise ValueError( 644 | "Can't download private playlists. Change your playlist's state to public." 645 | ) 646 | playlist = sp.playlist_tracks(sp_playlist) 647 | 648 | tracks_item = playlist['items'] 649 | 650 | while playlist['next']: 651 | playlist = sp.next(playlist) 652 | tracks_item.extend(playlist['items']) 653 | 654 | tracks = [item["track"] for item in tracks_item] 655 | tracks_info = [] 656 | track_id = [] 657 | # load tracks_id from synced.txt 658 | if os.path.exists("synced.txt"): 659 | with open("synced.txt", "r") as f: 660 | track_id = f.read().splitlines() 661 | updated_tracks = [] 662 | for track in tqdm(tracks): 663 | updated_tracks.append(track["id"]) 664 | if track["id"] in track_id: 665 | continue 666 | track_url = f"https://open.spotify.com/track/{track['id']}" 667 | track_info = get_track_info(track_url,sp) 668 | # make a progress bar 669 | 670 | tracks_info.append(track_info) 671 | # save the updated tracks_id to synced_updated.txt 672 | with open("synced_updated.txt", "w") as f: 673 | f.write("\n".join(updated_tracks)) 674 | return tracks_info 675 | 676 | def get_album_info(sp_album,sp): 677 | res = requests.get(sp_album) 678 | if res.status_code != 200: 679 | raise ValueError("Invalid Spotify playlist URL") 680 | # pl = sp.album(sp_album) 681 | 682 | playlist = sp.album_tracks(sp_album) 683 | 684 | tracks_item = playlist['items'] 685 | 686 | while playlist['next']: 687 | playlist = sp.next(playlist) 688 | tracks_item.extend(playlist['items']) 689 | 690 | # tracks = [item["track"] for item in tracks_item] 691 | tracks_info = [] 692 | track_id = [] 693 | # load tracks_id from synced.txt 694 | if os.path.exists("synced.txt"): 695 | with open("synced.txt", "r") as f: 696 | track_id = f.read().splitlines() 697 | updated_tracks = [] 698 | def process_track(track): 699 | updated_tracks.append(track["id"]) 700 | if track["id"] in track_id: 701 | return None 702 | track_url = f"https://open.spotify.com/track/{track['id']}" 703 | return get_track_info(track_url, sp) 704 | 705 | with ThreadPoolExecutor() as executor: 706 | results = list(tqdm(executor.map(process_track, tracks_item), total=len(tracks_item))) 707 | 708 | tracks_info.extend(filter(None, results)) 709 | # make a progress bar 710 | 711 | # save the updated tracks_id to synced_updated.txt 712 | with open("synced_updated.txt", "w") as f: 713 | f.write("\n".join(updated_tracks)) 714 | return tracks_info 715 | 716 | def main(page: ft.Page): 717 | page.adaptive = True 718 | page.appbar = app_bar() 719 | page.navigation_bar = nav_bar() 720 | # hide all dialogs in overlay 721 | folder_picker = FolderPicker() 722 | url = ft.TextField(keyboard_type=ft.KeyboardType.TEXT) 723 | pb = ft.ProgressBar() 724 | c1 = ft.Checkbox(label="Download only failed songs", value=False) 725 | # c2 = ft.Checkbox(label="Download high quality audio", value=False) 726 | c2 = ft.Checkbox(label="Download high quality audio (🙏 please get it from petreon or build from source to eneble this)", value=False,disabled=True) 727 | # def switch_to_yt_tab(e): 728 | # page.title= "Youtube" 729 | # youtube_tab.visible = True 730 | # spotify_tab.visible = False 731 | # page.navigation_bar.selected_index = 0 732 | # page.update 733 | 734 | # def switch_to_sp_tab(e): 735 | # page.title= "Spotify" 736 | # youtube_tab.visible = False 737 | # spotify_tab.visible = True 738 | # page.navigation_bar.selected_index = 1 739 | # page.update 740 | page.theme = ft.Theme(color_scheme_seed="Red") 741 | gesture_detector = GestureDetector() 742 | dd = ft.Dropdown( 743 | label="Song Exist Action", 744 | hint_text="What to do when that song already exist in your directory?", 745 | options=[ 746 | ft.dropdown.Option("Replace all"), 747 | ft.dropdown.Option("Skip all"), 748 | ], 749 | autofocus=True, 750 | ) 751 | # link = "https://www.youtube.com/watch?v=uelHwf8o7_U&list=PLGyF7r13ifSqeOxzefZfjiSgSoBK2W4fQ" 752 | # exists_action ="Replace all" 753 | def downloader(): 754 | try: 755 | t = ft.Text(value="") 756 | t2 = ft.Text(value = "0") 757 | pb = ft.ProgressBar(value=0) 758 | def button_clicked(e): 759 | link = url.value 760 | exists_action = dd.value 761 | t.value = "Downloading" 762 | t.update() 763 | b.disabled = True 764 | b.update() 765 | custom_labels = { 766 | "Replace all": "RA", 767 | "Skip all": "SA", 768 | "Determine while downloading from CLI": "", 769 | } 770 | global file_exists_action 771 | file_exists_action = custom_labels[exists_action] 772 | use_spotify_for_metadata = True 773 | try: 774 | load_dotenv() 775 | SPOTIPY_CLIENT_ID = os.getenv('SPOTIPY_CLIENT_ID') 776 | SPOTIPY_CLIENT_SECRET = os.getenv('SPOTIPY_CLIENT_SECRET') 777 | client_credentials_manager = SpotifyClientCredentials( 778 | client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET 779 | ) 780 | sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) 781 | except Exception as e: 782 | use_spotify_for_metadata = False 783 | print(f"Failed to connect to Spotify API: {e}") 784 | print("Continuing without Spotify API, some song metadata will not be added") 785 | exception_popup = popup(page,f"⚠️ Failed to connect to Spotify API: {e} . Continuing without Spotify API, some song metadata will not be added") 786 | page.open(exception_popup) 787 | # link = input("Enter YouTube Playlist URL: ✨") 788 | 789 | yt_playlist = Playlist(link) 790 | 791 | 792 | 793 | totalVideoCount = len(yt_playlist.videos) 794 | print("Total videos in playlist: 🎦", totalVideoCount) 795 | 796 | for index, video in enumerate(yt_playlist.videos): 797 | try: 798 | if c1.value: 799 | if os.path.exists("failed_downloads.txt"): 800 | with open("failed_downloads.txt", "r") as f: 801 | failed_songs = f.read().splitlines() 802 | if video.title not in failed_songs: 803 | continue 804 | print("Downloading: "+video.title) 805 | t2.value = f"{index+1}/{totalVideoCount}" 806 | pb.value = ((index+1)/totalVideoCount) 807 | 808 | view.update() 809 | t2.update() 810 | pb.update() 811 | 812 | audio = download_yt(video,video.title) 813 | if audio: 814 | if(use_spotify_for_metadata): 815 | try: 816 | track_url = search_spotify(f"{video.author} {video.title}",sp) 817 | except Exception as e: 818 | print(e) 819 | track_url = None 820 | if not track_url: 821 | track_info = get_track_info_youtube(video) 822 | else: 823 | track_info = get_track_info_spotify(track_url,sp) 824 | else: 825 | track_info = get_track_info_youtube(video) 826 | 827 | set_metadata(track_info, audio,"") 828 | os.replace(audio, f"{music_folder_path}{os.path.basename(audio)}") 829 | except Exception as e: 830 | print(f"Failed to download {video.title} due to: {e}") 831 | with open("failed_downloads.txt", "a") as f: 832 | f.write(f"{video.title}\n") 833 | continue 834 | t.value = "Downloaded" 835 | t2.value = "" 836 | t.update() 837 | b.disabled = False 838 | b.update() 839 | print("All videos downloaded successfully!") 840 | b = ft.ElevatedButton("Download Playlist", width=200000, on_click=button_clicked) 841 | view = ft.Container( 842 | 843 | content = ft.Column( 844 | [ 845 | b, 846 | ft.Container( 847 | # image_src=img, 848 | # image_opacity= 0, 849 | # image_fit= ft.ImageFit.COVER, 850 | padding=10, 851 | content=ft.Column([ 852 | ft.Divider(opacity=0), 853 | t, 854 | pb, 855 | t2, 856 | ft.Divider(opacity=0)]), 857 | 858 | ) 859 | 860 | ],) 861 | ) 862 | return view 863 | # return "All videos downloaded successfully!" 864 | except Exception as e: 865 | print(e) 866 | exception_popup = popup(page,f"⚠️ Failed to download. make sure all the options are properly selected, and the link is correct. restart and try again") 867 | page.open(exception_popup) 868 | 869 | def downloader_spotify(): 870 | t = ft.Text(value="") 871 | t2 = ft.Text(value = "0") 872 | pb = ft.ProgressBar(value=0) 873 | def button_clicked(e): 874 | print("Downloading: here you will se a progress bar. if that progress bar is stuck that means, spotify is rate limiting you. wait for a while and try again or download the 'no spotify key' version. for now there is no work around this. sorry for the inconvenience") 875 | link = url.value 876 | exists_action = dd.value 877 | t.value = "Fetching Playlist meta data (dont freak out if it takes a while 😅 it will take about a minute for 300 songs)" 878 | t.update() 879 | b.disabled = True 880 | b.update() 881 | try: 882 | custom_labels = { 883 | "Replace all": "RA", 884 | "Skip all": "SA", 885 | "Determine while downloading from CLI": "", 886 | } 887 | global file_exists_action 888 | file_exists_action = custom_labels[exists_action] 889 | use_spotify_for_metadata = True 890 | try: 891 | load_dotenv() 892 | SPOTIPY_CLIENT_ID = os.getenv('SPOTIPY_CLIENT_ID') 893 | SPOTIPY_CLIENT_SECRET = os.getenv('SPOTIPY_CLIENT_SECRET') 894 | client_credentials_manager = SpotifyClientCredentials( 895 | client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET 896 | ) 897 | sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) 898 | except Exception as e: 899 | use_spotify_for_metadata = False 900 | print(f"Failed to connect to Spotify API: {e}") 901 | print("Continuing without Spotify API, some song metadata will not be added") 902 | exception_popup = popup(page,f"⚠️ Failed to connect to Spotify API: {e} . Continuing without Spotify API, some song metadata will not be added") 903 | page.open(exception_popup) 904 | # link = input("Enter YouTube Playlist URL: ✨") 905 | 906 | if "track" in link: 907 | songs = [get_track_info(link,sp)] 908 | elif "playlist" in link: 909 | songs = get_playlist_info(link,sp) 910 | else: 911 | songs = get_album_info(link,sp) 912 | # pickle the songs list 913 | # with open("songs.pkl", "wb") as f: 914 | # pickle.dump(songs, f) 915 | # with open("songs.pkl", "rb") as f: 916 | # songs = pickle.load(f) 917 | t.value = "Starting Download" 918 | t.update() 919 | downloaded = 0 920 | song_name_list = [] 921 | if os.path.exists("song_names.txt"): 922 | if input("only download the songs that are not already downloaded [y/n]: ").strip() == "y": 923 | with open("song_names.txt", "r") as f: 924 | song_name_list = f.read().splitlines() 925 | # check if downloaded.txt exists 926 | # if os.path.exists("downloaded.txt"): 927 | # if input("Resume download? [y/n]: ").strip() == "y": 928 | # with open("downloaded.txt", "r") as f: 929 | # downloaded = int(f.read()) 930 | totalVideoCount = len(songs) 931 | for i, track_info in enumerate(songs): 932 | try: 933 | # check if the song is already downloaded at f"{music_folder_path}{search_term}.mp3" 934 | if dd.value == "Skip all": 935 | if os.path.exists(f"{music_folder_path}{track_info['track_title']}.mp3"): 936 | print("Skipping: "+track_info["track_title"]) 937 | continue 938 | if c1.value: 939 | if os.path.exists("failed_downloads.txt"): 940 | with open("failed_downloads.txt", "r", encoding="utf-8") as f: 941 | failed_songs = f.read().splitlines() 942 | if track_info["track_title"] not in failed_songs: 943 | continue 944 | print("Downloading: "+track_info["track_title"]) 945 | t2.value = f"{i+1}/{totalVideoCount}" 946 | pb.value = ((i+1)/totalVideoCount) 947 | t.value = "Downloading: "+track_info["track_title"] 948 | t.update() 949 | view.update() 950 | t2.update() 951 | pb.update() 952 | if track_info["track_title"] in song_name_list: 953 | continue 954 | if downloaded > i: 955 | continue 956 | search_term = f"{track_info['artist_name']} {track_info['track_title']} audio" 957 | lyrics = "" 958 | if c2.value: 959 | song = download_high_quality(search_term) 960 | if song == "No songs found for the query.": 961 | try: 962 | print("No songs found for the query in high quality song server." , search_term) 963 | print("Trying to download from youtube") 964 | video_link = find_youtube(search_term) 965 | yt = YouTube(video_link) 966 | audio = download_yt(yt,search_term) 967 | except Exception as e: 968 | print("No songs found for the query in high quality song server." , search_term) 969 | tt = track_info["track_title"] 970 | with open("failed_downloads.txt", "a", encoding="utf-8") as f: 971 | f.write(f"{tt}\n") 972 | print("Skipping... adding to failed_downloads.txt redownload with low quality in next run" ) 973 | continue 974 | else: 975 | artist = song['primary_artists'] 976 | # compare the artist name from the song and the artist name from the track_info 977 | if (difflib.SequenceMatcher(None, artist.lower(), track_info["artist_name"].lower()).ratio()<0.4): 978 | try: 979 | print("songs found for the query in high quality song server. very different from the one in spotify" , search_term) 980 | print("Trying to download from youtube") 981 | video_link = find_youtube(search_term) 982 | yt = YouTube(video_link) 983 | audio = download_yt(yt,search_term) 984 | except Exception as e: 985 | print("No songs found for the query in high quality song server." , search_term) 986 | tt = track_info["track_title"] 987 | with open("failed_downloads.txt", "a", encoding="utf-8") as f: 988 | f.write(f"{tt}\n") 989 | print("Skipping... adding to failed_downloads.txt redownload with low quality in next run" ) 990 | continue 991 | 992 | elif (difflib.SequenceMatcher(None, artist.lower(), track_info["artist_name"].lower()).ratio()<0.85): 993 | print("Artist name mismatch. Skipping...") 994 | tt = track_info["track_title"] 995 | aa = track_info["artist_name"] 996 | with open("mismatched_downloads.txt", "a", encoding="utf-8") as f: 997 | f.write(f"{tt} || Orignal artist : {aa} || Downloaded artist: {artist}\n") 998 | continue 999 | audio = song["mp3"] 1000 | lyrics = song["lyrics"] 1001 | else: 1002 | video_link = find_youtube(search_term) 1003 | yt = YouTube(video_link) 1004 | audio = download_yt(yt,search_term) 1005 | if audio: 1006 | # track_info["track_number"] = downloaded + 1 1007 | set_metadata(track_info, audio,lyrics) 1008 | sanitized_title = sanitize_filename(track_info['track_title']) 1009 | destination_path = os.path.join(music_folder_path, f"{sanitized_title}.mp3") 1010 | os.replace(audio, destination_path) 1011 | downloaded += 1 1012 | # save the downloaded count to a file 1013 | with open("downloaded.txt", "w") as f: 1014 | f.write(str(downloaded)) 1015 | else: 1016 | print("File exists. Skipping...") 1017 | except Exception as e: 1018 | tt = track_info["track_title"] 1019 | print(f"Failed to download {tt} due to: {e}") 1020 | with open("failed_downloads.txt", "a", encoding="utf-8") as f: 1021 | f.write(f"{tt}\n") 1022 | continue 1023 | t.value = "Downloaded" 1024 | t2.value = "" 1025 | t.update() 1026 | b.disabled = False 1027 | b.update() 1028 | print("All songs downloaded successfully!") 1029 | print("Few more steps to go. 🚀") 1030 | print("1. Open the downloaded folder and check if all the songs are downloaded.") 1031 | print("2. open mismatched_downloads.txt and check if any songs are mismatched. most of them should be fine but still manually check the songs. if it is not the song you wanted, delete the song from the folder.") 1032 | print("3. restart the app and download again but with high quality audio turned off. this will download the songs from youtube. make sure to select skip all in the song exist action dropdown.") 1033 | print("4. open failed_downloads.txt and download the songs that are failed to download.") 1034 | completion_popup = popup(page,"All songs downloaded successfully!\n Few more steps to go. 🚀 \n1. Open the downloaded folder and check if all the songs are downloaded. \n2. open mismatched_downloads.txt and check if any songs are mismatched. most of them should be fine but still manually check the songs. if it is not the song you wanted, delete the song from the folder.\n3. restart the app and download again but with high quality audio turned off. this will download the songs from youtube. make sure to select skip all in the song exist action dropdown.") 1035 | page.open(completion_popup) 1036 | except Exception as e: 1037 | print(e) 1038 | exception_popup = popup(page,f"⚠️ Failed to download. make sure all the options are properly selected, and the link is correct. restart and try again ({e})") 1039 | page.open(exception_popup) 1040 | b = ft.ElevatedButton("Download Playlist", width=200000, on_click=button_clicked) 1041 | view = ft.Container( 1042 | 1043 | content = ft.Column( 1044 | [ 1045 | b, 1046 | ft.Container( 1047 | # image_src=img, 1048 | # image_opacity= 0, 1049 | # image_fit= ft.ImageFit.COVER, 1050 | padding=10, 1051 | content=ft.Column([ 1052 | ft.Divider(opacity=0), 1053 | t, 1054 | pb, 1055 | t2, 1056 | ft.Divider(opacity=0)]), 1057 | 1058 | ) 1059 | 1060 | ],) 1061 | ) 1062 | return view 1063 | 1064 | def downloader_apple_music(): 1065 | try: 1066 | t = ft.Text(value="") 1067 | t2 = ft.Text(value = "0") 1068 | pb = ft.ProgressBar(value=0) 1069 | def button_clicked(e): 1070 | 1071 | link = url.value 1072 | exists_action = dd.value 1073 | t.value = "Fetching Playlist meta data (dont freak out if it takes a while 😅 it will take about a minute for 100 songs)" 1074 | t.update() 1075 | b.disabled = True 1076 | b.update() 1077 | custom_labels = { 1078 | "Replace all": "RA", 1079 | "Skip all": "SA", 1080 | "Determine while downloading from CLI": "", 1081 | } 1082 | global file_exists_action 1083 | file_exists_action = custom_labels[exists_action] 1084 | use_spotify_for_metadata = True 1085 | try: 1086 | load_dotenv() 1087 | SPOTIPY_CLIENT_ID = os.getenv('SPOTIPY_CLIENT_ID') 1088 | SPOTIPY_CLIENT_SECRET = os.getenv('SPOTIPY_CLIENT_SECRET') 1089 | client_credentials_manager = SpotifyClientCredentials( 1090 | client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET 1091 | ) 1092 | sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) 1093 | except Exception as e: 1094 | use_spotify_for_metadata = False 1095 | print(f"Failed to connect to Spotify API: {e}") 1096 | print("Continuing without Spotify API, some song metadata will not be added") 1097 | exception_popup = popup(page,f"⚠️ Failed to connect to Spotify API: {e} . Continuing without Spotify API, some song metadata will not be added") 1098 | page.open(exception_popup) 1099 | # link = input("Enter YouTube Playlist URL: ✨") 1100 | 1101 | am_playlist = apple.get_playlist(link) 1102 | 1103 | 1104 | 1105 | totalVideoCount = len(am_playlist) 1106 | print("Total songs in playlist:", totalVideoCount) 1107 | 1108 | for index, song in enumerate(am_playlist): 1109 | try: 1110 | # check if the song is already downloaded at f"{music_folder_path}{search_term}.mp3" 1111 | if dd.value == "Skip all": 1112 | if os.path.exists(f"{music_folder_path}{song}.mp3"): 1113 | print("Skipping: "+song) 1114 | continue 1115 | if c1.value: 1116 | if os.path.exists("failed_downloads.txt"): 1117 | with open("failed_downloads.txt", "r") as f: 1118 | failed_songs = f.read().splitlines() 1119 | if song not in failed_songs: 1120 | continue 1121 | print("Downloading: "+song) 1122 | t2.value = f"{index+1}/{totalVideoCount}" 1123 | pb.value = ((index+1)/totalVideoCount) 1124 | 1125 | view.update() 1126 | t2.update() 1127 | pb.update() 1128 | lyrics = "" 1129 | if c2.value: 1130 | song_js = download_high_quality(song) 1131 | if song_js == "No songs found for the query.": 1132 | try: 1133 | print("No songs found for the query in high quality song server." , song) 1134 | print("Trying to download from youtube") 1135 | video_link = find_youtube(song) 1136 | yt = YouTube(video_link) 1137 | audio = download_yt(yt,song) 1138 | except Exception as e: 1139 | print("No songs found for the query in high quality song server." , song) 1140 | with open("failed_downloads.txt", "a", encoding="utf-8") as f: 1141 | f.write(f"{song}\n") 1142 | print("Skipping... adding to failed_downloads.txt redownload with low quality in next run" ) 1143 | continue 1144 | else: 1145 | audio = song_js["mp3"] 1146 | lyrics = song_js["lyrics"] 1147 | else: 1148 | video_link = find_youtube(song) 1149 | yt = YouTube(video_link) 1150 | audio = download_yt(yt,song) 1151 | if audio: 1152 | if(use_spotify_for_metadata): 1153 | try: 1154 | spotify_search_term = song.replace(" by", "").replace(" audio", "") 1155 | track_url = search_spotify(spotify_search_term,sp) 1156 | except Exception as e: 1157 | print(e) 1158 | track_url = None 1159 | if not track_url: 1160 | track_info = get_track_info_youtube(yt) 1161 | else: 1162 | track_info = get_track_info_spotify(track_url,sp) 1163 | else: 1164 | track_info = get_track_info_youtube(yt) 1165 | 1166 | set_metadata(track_info, audio,lyrics) 1167 | os.replace(audio, f"{music_folder_path}{os.path.basename(audio)}") 1168 | except Exception as e: 1169 | print(f"Failed to download {song} due to: {e}") 1170 | with open("failed_downloads.txt", "a") as f: 1171 | f.write(f"{song}\n") 1172 | continue 1173 | t.value = "Downloaded" 1174 | t2.value = "" 1175 | t.update() 1176 | b.disabled = False 1177 | b.update() 1178 | print("All songs downloaded successfully!") 1179 | print("Few more steps to go. 🚀") 1180 | print("1. Open the downloaded folder and check if all the songs are downloaded.") 1181 | print("2. some songs downloaded from the high quality audio server might not be the song you wanted. please check the songs manually and delete the songs that are not the song you wanted.") 1182 | print("3. restart the app and download again but with high quality audio turned off. this will download the songs from youtube. make sure to select skip all in the song exist action dropdown.") 1183 | print("4. open failed_downloads.txt and download the songs that are failed to download.") 1184 | completion_popup = popup(page,"All songs downloaded successfully!\n Few more steps to go. 🚀 \n1. Open the downloaded folder and check if all the songs are downloaded. \n2. some songs downloaded from the high quality audio server might not be the song you wanted. please check the songs manually and delete the songs that are not the song you wanted.\n3. restart the app and download again but with high quality audio turned off. this will download the songs from youtube. make sure to select skip all in the song exist action dropdown.") 1185 | page.open(completion_popup) 1186 | b = ft.ElevatedButton("Download Playlist", width=200000, on_click=button_clicked) 1187 | view = ft.Container( 1188 | 1189 | content = ft.Column( 1190 | [ 1191 | b, 1192 | ft.Container( 1193 | # image_src=img, 1194 | # image_opacity= 0, 1195 | # image_fit= ft.ImageFit.COVER, 1196 | padding=10, 1197 | content=ft.Column([ 1198 | ft.Divider(opacity=0), 1199 | t, 1200 | pb, 1201 | t2, 1202 | ft.Divider(opacity=0)]), 1203 | 1204 | ) 1205 | 1206 | ],) 1207 | ) 1208 | return view 1209 | # return "All videos downloaded successfully!" 1210 | except Exception as e: 1211 | print(e) 1212 | exception_popup = popup(page,f"⚠️ Failed to download. make sure all the options are properly selected, and the link is correct. restart and try again") 1213 | page.open(exception_popup) 1214 | 1215 | youtube_tab = ft.Container( 1216 | ft.SafeArea( 1217 | content=ft.Column( 1218 | [ 1219 | ft.Divider(opacity=0, height= 20), 1220 | folder_picker, 1221 | ft.Divider(opacity=0, height= 20), 1222 | ft.Text("Enter Youtube playlist url:"), 1223 | url, 1224 | ft.Divider(opacity=0), 1225 | dd, 1226 | ft.Divider(opacity=0), 1227 | # ft.ElevatedButton(text="Download Playlist",width=200000), 1228 | c1, 1229 | ft.Divider(opacity=0), 1230 | downloader(), 1231 | # ft.FilledButton("sp",on_click=switch_to_sp_tab) 1232 | gesture_detector.detector, 1233 | 1234 | ] 1235 | ) 1236 | ), 1237 | visible= True 1238 | ) 1239 | 1240 | spotify_tab = ft.Container( 1241 | ft.SafeArea( 1242 | content=ft.Column( 1243 | [ 1244 | ft.Divider(opacity=0, height= 20), 1245 | folder_picker, 1246 | ft.Divider(opacity=0, height= 20), 1247 | ft.Text("Enter Spotify playlist or album url:"), 1248 | url, 1249 | ft.Divider(opacity=0), 1250 | dd, 1251 | ft.Divider(opacity=0), 1252 | ft.Row([c1,c2]), 1253 | ft.Divider(opacity=0), 1254 | # ft.ElevatedButton(text="Download Playlist",width=200000), 1255 | downloader_spotify(), 1256 | # ft.FilledButton("yt",on_click=switch_to_yt_tab) 1257 | gesture_detector.detector, 1258 | ] 1259 | ) 1260 | ), 1261 | visible= False 1262 | ) 1263 | apple_music_tab = ft.Container( 1264 | ft.SafeArea( 1265 | content=ft.Column( 1266 | [ 1267 | ft.Divider(opacity=0, height= 20), 1268 | folder_picker, 1269 | ft.Divider(opacity=0, height= 20), 1270 | ft.Text("Enter Apple Music playlist or album url:"), 1271 | url, 1272 | ft.Divider(opacity=0), 1273 | dd, 1274 | ft.Divider(opacity=0), 1275 | ft.Row([c1,c2]), 1276 | ft.Divider(opacity=0), 1277 | # ft.ElevatedButton(text="Download Playlist",width=200000), 1278 | downloader_apple_music(), 1279 | # ft.FilledButton("yt",on_click=switch_to_yt_tab) 1280 | gesture_detector.detector, 1281 | ] 1282 | ) 1283 | ), 1284 | visible= False 1285 | ) 1286 | spotify_client_id = ft.TextField(keyboard_type=ft.KeyboardType.TEXT) 1287 | spotify_client_secret = ft.TextField(keyboard_type=ft.KeyboardType.TEXT) 1288 | spotify_client_id.value = os.getenv('SPOTIPY_CLIENT_ID') 1289 | spotify_client_secret.value = os.getenv('SPOTIPY_CLIENT_SECRET') 1290 | def save_app_settings(e): 1291 | try: 1292 | env_str = "SPOTIPY_CLIENT_ID=" + spotify_client_id.value + "\nSPOTIPY_CLIENT_SECRET=" + spotify_client_secret.value 1293 | with open(".env", "a+") as f: 1294 | f.seek(0) # Move the cursor to the beginning of the file 1295 | f.truncate() # Clear the file content 1296 | f.write(env_str) 1297 | except Exception as e: 1298 | print(e) 1299 | return "app settings update failed" 1300 | return "app settings updated" 1301 | def yt_page_launch(e): 1302 | e.control.page.launch_url('https://youtu.be/vT43uBHq974') 1303 | def petreon_page_launch(e): 1304 | e.control.page.launch_url('https://www.patreon.com/c/Predacons') 1305 | def github_page_launch(e): 1306 | e.control.page.launch_url('https://github.com/shouryashashank/Trackster') 1307 | def email_page_launch(e): 1308 | e.control.page.launch_url('https://www.patreon.com/messages/ffd73e51aa264a61842c446763dbaff9?mode=campaign&tab=chats') 1309 | 1310 | settings_tab = ft.Container( 1311 | ft.SafeArea( 1312 | content=ft.Column( 1313 | [ 1314 | ft.Row( 1315 | [ 1316 | ft.Text("") 1317 | ], 1318 | alignment=ft.MainAxisAlignment.SPACE_BETWEEN 1319 | ), 1320 | ft.Text("Spotify client id:"), 1321 | spotify_client_id, 1322 | ft.Text("Spotify client secret:"), 1323 | spotify_client_secret, 1324 | ft.ElevatedButton("Save",on_click=save_app_settings), 1325 | ft.TextButton("How To Get Spotify api api Keys",on_click=yt_page_launch), 1326 | ft.TextButton("Contact support",on_click=email_page_launch), 1327 | ft.TextButton("Get version with api key already added.",on_click=petreon_page_launch), 1328 | ft.TextButton("Help me buy a new phone",on_click=petreon_page_launch), 1329 | ft.TextButton("See source code",on_click=github_page_launch) 1330 | 1331 | ] 1332 | ) 1333 | ), 1334 | visible= False 1335 | ) 1336 | page.spotify_tab=spotify_tab 1337 | page.youtube_tab = youtube_tab 1338 | page.apple_music_tab = apple_music_tab 1339 | page.settings_tab = settings_tab 1340 | page.overlay.extend([ get_directory_dialog]) 1341 | 1342 | page.add( 1343 | youtube_tab,spotify_tab,apple_music_tab,settings_tab 1344 | ) 1345 | for i in range(0, 101): 1346 | pb.value = i * 0.01 1347 | time.sleep(0.1) 1348 | page.update() 1349 | 1350 | 1351 | ft.app(target=main) -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import flet as ft 2 | import time 3 | import os 4 | from pytube import Playlist 5 | from moviepy.editor import * 6 | from mutagen.easyid3 import EasyID3 7 | import requests 8 | import spotipy 9 | from spotipy.oauth2 import SpotifyClientCredentials 10 | from mutagen.id3 import APIC, ID3 11 | import urllib.request 12 | from tqdm import tqdm 13 | from dotenv import load_dotenv 14 | import os 15 | import re 16 | import shutil 17 | import time 18 | import urllib.request 19 | import pickle 20 | from tqdm import tqdm 21 | import spotipy 22 | from moviepy.editor import * 23 | from mutagen.easyid3 import EasyID3 24 | from mutagen.id3 import APIC, ID3 25 | from pytube import YouTube 26 | import pytube.exceptions 27 | from rich.console import Console 28 | from spotipy.oauth2 import SpotifyClientCredentials 29 | from yarl import URL 30 | import ssl 31 | import sys, io 32 | from bs4 import BeautifulSoup 33 | import apple 34 | import yt_dlp 35 | from yt_dlp.utils import download_range_func 36 | from moviepy.editor import * 37 | import base64 38 | from pyDes import * 39 | import requests 40 | import os 41 | import urllib.request 42 | import time 43 | from moviepy.editor import AudioFileClip 44 | from mutagen.id3 import ID3, TIT2, TPE1, TPE2, TALB, TDRC, TRCK, TSRC, USLT, APIC 45 | import asyncio 46 | import aiohttp 47 | from aiohttp import ClientTimeout 48 | import difflib 49 | from search import Search, DownloadSong, Song 50 | 51 | 52 | 53 | # buffer = io.StringIO() 54 | # sys.stdout = sys.stderr = buffer 55 | 56 | ssl._create_default_https_context = ssl._create_unverified_context 57 | # pyinstaller --noconfirm --onefile --windowed --icon "D:\Code\github\music\Trackster\icon_for_an_app_called_trakster_used_to_download_spotify_and_youtube_playlist-removebg-preview.ico" --name "Trackster_101_Fix_Premium" "D:\Code\github\music\Trackster\main.py" 58 | file_exists_action="" 59 | failed_download = False 60 | high_quality = False 61 | search_base_url = "https://www.jiosaavn.com/api.php?__call=autocomplete.get&_format=json&_marker=0&cc=in&includeMetaTags=1&query=" 62 | song_base_url = "https://www.jiosaavn.com/api.php?__call=song.getDetails&cc=in&_marker=0%3F_marker%3D0&_format=json&pids=" 63 | lyrics_base_url = "https://www.jiosaavn.com/api.php?__call=lyrics.getLyricvideo_files&ctx=web6dot0&api_version=4&_format=json&_marker=0%3F_marker%3D0&lyrics_id=" 64 | music_folder_path = "music-yt/" # path to save the downloaded music 65 | # SPOTIPY_CLIENT_ID = "" # Spotify API client ID # keep blank if you dont need spotify metadata 66 | # SPOTIPY_CLIENT_SECRET = "" # Spotify API client secret 67 | 68 | def sanitize_filename(filename): 69 | return re.sub(r'[<>:"/\\|?*]', '', filename) 70 | 71 | def prompt_exists_action(): 72 | """ask the user what happens if the file being downloaded already exists""" 73 | global file_exists_action 74 | if file_exists_action == "SA": # SA == 'Skip All' 75 | return False 76 | elif file_exists_action == "RA": # RA == 'Replace All' 77 | return True 78 | 79 | print("This file already exists.") 80 | while True: 81 | resp = ( 82 | input("replace[R] | replace all[RA] | skip[S] | skip all[SA]: ") 83 | .upper() 84 | .strip() 85 | ) 86 | if resp in ("RA", "SA"): 87 | file_exists_action = resp 88 | if resp in ("R", "RA"): 89 | return True 90 | elif resp in ("S", "SA"): 91 | return False 92 | print("---Invalid response---") 93 | 94 | def make_alpha_numeric(string): 95 | return ''.join(char for char in string if char.isalnum()) 96 | 97 | def download_yt(yt,search_term): 98 | """download the video in mp3 format from youtube""" 99 | # remove chars that can't be in a windows file name 100 | yt.title = "".join([c for c in yt.title if c not in ['/', '\\', '|', '?', '*', ':', '>', '<', '"']]) 101 | # don't download existing files if the user wants to skip them 102 | exists = os.path.exists(f"{music_folder_path}{yt.title}.mp3") 103 | if exists and not prompt_exists_action(): 104 | return False 105 | 106 | # download the music 107 | yt_opts = { 108 | 'extract_audio': True, 109 | 'format': 'bestaudio', 110 | 'outtmpl': f"{music_folder_path}tmp/{yt.title}.mp4", 111 | } 112 | with yt_dlp.YoutubeDL(yt_opts) as ydl: 113 | ydl.download(yt.watch_url) 114 | # max_retries = 3 115 | # attempt = 0 116 | # video = None 117 | 118 | # while attempt < max_retries: 119 | # try: 120 | # video = yt.streams.filter(only_audio=True).first() 121 | # if video: 122 | # break 123 | # except Exception as e: 124 | # print(f"Attempt {attempt + 1} {search_term} failed due to: {e}") 125 | # attempt += 1 126 | # if not video: 127 | # print(f"Failed to download {search_term}") 128 | # # check if a file named failed_downloads.txt exists if not create one and append the failed download 129 | # if not os.path.exists("failed_downloads.txt"): 130 | # with open("failed_downloads.txt", "w") as f: 131 | # f.write(f"{search_term}\n") 132 | # else: 133 | # with open("failed_downloads.txt", "a") as f: 134 | # f.write(f"{search_term}\n") 135 | # return False 136 | # vid_file = video.download(output_path=f"{music_folder_path}tmp") 137 | # # convert the downloaded video to mp3 138 | # base = os.path.splitext(vid_file)[0] 139 | # audio_file = base + ".mp3" 140 | # mp4_no_frame = AudioFileClip(vid_file) 141 | # mp4_no_frame.write_audiofile(audio_file, logger=None) 142 | # mp4_no_frame.close() 143 | # os.remove(vid_file) 144 | # os.replace(audio_file, f"{music_folder_path}tmp/{yt.title}.mp3") 145 | video_file = f"{music_folder_path}tmp/{yt.title}.mp4" 146 | audio_file = f"{music_folder_path}tmp/{yt.title}.mp3" 147 | FILETOCONVERT = AudioFileClip(video_file) 148 | FILETOCONVERT.write_audiofile(audio_file) 149 | FILETOCONVERT.close() 150 | os.remove(video_file) 151 | audio_file = f"{music_folder_path}tmp/{yt.title}.mp3" 152 | return audio_file 153 | 154 | def decrypt_url(url): 155 | des_cipher = des(b"38346591", ECB, b"\0\0\0\0\0\0\0\0", 156 | pad=None, padmode=PAD_PKCS5) 157 | enc_url = base64.b64decode(url.strip()) 158 | dec_url = des_cipher.decrypt(enc_url, padmode=PAD_PKCS5).decode('utf-8') 159 | dec_url = dec_url.replace("_96.mp4", "_320.mp4") 160 | return dec_url 161 | 162 | def search_song(query): 163 | search_url = search_base_url + query 164 | response = requests.get(search_url) 165 | # First, try to find a song in the topquery data if available 166 | try: 167 | topquery_data = response.json().get('topquery', {}).get('data', []) 168 | for item in topquery_data: 169 | if item.get('type') == 'song' and item.get('id'): 170 | # Use the first song id found in topquery data 171 | best_song_id = item['id'] 172 | best_diff = 1.0 # highest similarity; we will exit early if exact match found 173 | break 174 | else: 175 | best_song_id = None 176 | best_diff = 0 177 | except Exception: 178 | best_song_id = None 179 | best_diff = 0 180 | 181 | # If a topquery song wasn't found, fall back to the existing logic 182 | if not best_song_id: 183 | songs = response.json().get('songs', {}).get('data', []) 184 | if not songs: 185 | return "No songs found for the query." 186 | song_id = response.json()['songs']['data'][0]['id'] 187 | best_diff = 0 188 | best_song_id = song_id 189 | 190 | for song_data in songs: 191 | try: 192 | sid = song_data['id'] 193 | output_query = f"{song_data['title']} {song_data['more_info']['primary_artists']} {song_data['album']}" 194 | diff_ratio = difflib.SequenceMatcher(None, query.lower(), output_query.lower()).ratio() 195 | if diff_ratio > best_diff: 196 | best_diff = diff_ratio 197 | best_song_id = sid 198 | if diff_ratio == 1: 199 | break 200 | except Exception as e: 201 | print(f"Error processing song data: {e}") 202 | 203 | if not best_song_id: 204 | return "No suitable song found." 205 | 206 | song_url = song_base_url + best_song_id 207 | response = requests.get(song_url) 208 | song_url = response.json()[best_song_id]['encrypted_media_url'] 209 | primary_artists = response.json()[best_song_id]['primary_artists'] 210 | album = response.json()[best_song_id]['album'] 211 | song = response.json()[best_song_id]['song'] 212 | release_date = response.json()[best_song_id]['release_date'] 213 | 214 | has_lyrics = response.json()[best_song_id]['has_lyrics'] == 'true' 215 | lyrics = "" 216 | if has_lyrics: 217 | lyrics_url = lyrics_base_url + best_song_id 218 | try: 219 | lyrics_response = requests.get(lyrics_url) 220 | lyrics = lyrics_response.json()['lyrics'] 221 | except Exception as e: 222 | print(f"Failed to get lyrics for {song}: {e}") 223 | 224 | return { 225 | "url": decrypt_url(song_url), 226 | "primary_artists": primary_artists, 227 | "album": album, 228 | "song": song, 229 | "release_date": release_date, 230 | "lyrics": lyrics 231 | } 232 | 233 | def download_high_quality(search_term): 234 | song = search_song(search_term) 235 | if song == "No songs found for the query.": return song 236 | song_url = song['url'] 237 | if not isinstance(song, dict): 238 | return "Unexpected response format." 239 | file = f"{music_folder_path}{os.path.basename(song['song'])}.mp3" 240 | # check if the file already exists 241 | if os.path.exists(file): 242 | if not prompt_exists_action(): 243 | return "File already exists." 244 | response = requests.get(song_url) 245 | # create new folder if it doesn't exist "tmp" 246 | if not os.path.exists(f"{music_folder_path}tmp"): 247 | os.makedirs(f"{music_folder_path}tmp") 248 | sanitized_song_name = sanitize_filename(song['song']) 249 | video_file = f"{music_folder_path}tmp/{sanitized_song_name}.mp4" 250 | audio_file = f"{music_folder_path}tmp/{sanitized_song_name}.mp3" 251 | with open(video_file, "wb") as f: 252 | f.write(response.content) 253 | FILETOCONVERT = AudioFileClip(video_file) 254 | FILETOCONVERT.write_audiofile(audio_file,bitrate="3000k") 255 | FILETOCONVERT.close() 256 | os.remove(video_file) 257 | song["mp3"] = audio_file 258 | return song 259 | # def set_metadata(metadata, file_path,lyrics): 260 | # """adds metadata to the downloaded mp3 file""" 261 | 262 | # mp3file = ID3(file_path) 263 | 264 | # # add metadata 265 | # mp3file["albumartist"] = metadata["artist_name"] 266 | # mp3file["artist"] = metadata["artists"] 267 | # mp3file["album"] = metadata["album_name"] 268 | # mp3file["title"] = metadata["track_title"] 269 | # mp3file["date"] = metadata["release_date"] 270 | # mp3file["tracknumber"] = str(metadata["track_number"]) 271 | # mp3file["isrc"] = metadata["isrc"] 272 | # if lyrics != "": 273 | # ulyrics = mp3file.getall('USLT')[0] 274 | 275 | # # change the lyrics text 276 | # ulyrics.text = lyrics 277 | # mp3file.setall('USLT', [ulyrics]) 278 | # mp3file.save() 279 | 280 | def set_metadata(metadata, file_path, lyrics): 281 | """adds metadata to the downloaded mp3 file""" 282 | 283 | mp3file = ID3(file_path) 284 | 285 | # add metadata 286 | mp3file["TPE1"] = TPE1(encoding=3, text=metadata["artist_name"]) 287 | mp3file["TPE2"] = TPE2(encoding=3, text=metadata["artists"]) 288 | mp3file["TALB"] = TALB(encoding=3, text=metadata["album_name"]) 289 | mp3file["TIT2"] = TIT2(encoding=3, text=metadata["track_title"]) 290 | mp3file["TDRC"] = TDRC(encoding=3, text=metadata["release_date"]) 291 | mp3file["TRCK"] = TRCK(encoding=3, text=str(metadata["track_number"])) 292 | mp3file["TSRC"] = TSRC(encoding=3, text=metadata["isrc"]) 293 | if lyrics != "": 294 | # Check if USLT frame exists, if not create a new one 295 | if mp3file.getall('USLT'): 296 | ulyrics = mp3file.getall('USLT')[0] 297 | ulyrics.text = lyrics 298 | else: 299 | ulyrics = USLT(encoding=3, desc='', text=lyrics) 300 | mp3file.add(ulyrics) 301 | mp3file.save() 302 | 303 | # add album cover 304 | audio = ID3(file_path) 305 | with urllib.request.urlopen(metadata["album_art"]) as albumart: 306 | audio["APIC"] = APIC( 307 | encoding=3, 308 | mime='image/jpeg', 309 | type=3, 310 | desc=u'Cover', 311 | data=albumart.read() 312 | ) 313 | audio.save() 314 | 315 | # add album cover 316 | audio = ID3(file_path) 317 | with urllib.request.urlopen(metadata["album_art"]) as albumart: 318 | audio["APIC"] = APIC( 319 | encoding=3, mime="image/jpeg", type=3, desc="Cover", data=albumart.read() 320 | ) 321 | audio.save(v2_version=3) 322 | 323 | def search_spotify(search_term : str, sp)->str: 324 | """search for the track on spotify""" 325 | search_results = sp.search(search_term, type="track", limit=1) 326 | if search_results["tracks"]["total"] == 0: 327 | return None 328 | track = search_results["tracks"]["items"][0] 329 | return track["external_urls"]["spotify"] 330 | 331 | def get_track_info_spotify(track_url,sp): 332 | res = requests.get(track_url) 333 | if res.status_code != 200: 334 | # retry 3 times 335 | for i in range(3): 336 | res = requests.get(track_url) 337 | if res.status_code == 200: 338 | break 339 | if res.status_code != 200: 340 | print("Invalid Spotify track URL") 341 | 342 | track = sp.track(track_url) 343 | 344 | track_metadata = { 345 | "artist_name": track["artists"][0]["name"], 346 | "track_title": track["name"], 347 | "track_number": track["track_number"], 348 | "isrc": track["external_ids"]["isrc"], 349 | "album_art": track["album"]["images"][1]["url"], 350 | "album_name": track["album"]["name"], 351 | "release_date": track["album"]["release_date"], 352 | "artists": [artist["name"] for artist in track["artists"]], 353 | } 354 | 355 | return track_metadata 356 | 357 | def get_track_info_youtube(video): 358 | 359 | track_metadata = { 360 | "artist_name": video.author, 361 | "track_title": video.title, 362 | "track_number": 0, 363 | "isrc": "", 364 | "album_art": video.thumbnail_url, 365 | "album_name": video.author, 366 | "release_date": video.publish_date.strftime("%Y-%m-%d"), 367 | "artists": [video.author], 368 | } 369 | 370 | return track_metadata 371 | 372 | def ensure_folder_path_ends_with_slash(folder_path): 373 | if not folder_path.endswith(os.sep): 374 | folder_path += os.sep 375 | return folder_path 376 | 377 | 378 | 379 | 380 | 381 | 382 | # Open directory dialog 383 | def get_directory_result(e: ft.FilePickerResultEvent): 384 | directory_path.value = e.path if e.path else "Cancelled!" 385 | directory_path.update() 386 | global music_folder_path 387 | music_folder_path = ensure_folder_path_ends_with_slash(e.path) 388 | print(music_folder_path) 389 | 390 | get_directory_dialog = ft.FilePicker(on_result=get_directory_result) 391 | directory_path = ft.Text() 392 | def set_theme(e,color): 393 | e.control.page.theme = ft.Theme(color_scheme_seed=color) 394 | e.control.page.update() 395 | def progress_bar(): 396 | t = ft.Text(value="") 397 | t2 = ft.Text(value = "0") 398 | pb = ft.ProgressBar(value=0) 399 | # img = "https://picsum.photos/200/200?0" 400 | def button_clicked(e): 401 | t.value = "Downloading" 402 | t.update() 403 | b.disabled = True 404 | b.update() 405 | 406 | for i in range(0, 101): 407 | # view.content.controls[0].image_src = f"https://picsum.photos/id/{i+10}/200/300" 408 | # view.content.controls[0].image_opacity = 0.2 409 | t2.value = i 410 | pb.value = i * 0.01 411 | time.sleep(0.1) 412 | view.update() 413 | t2.update() 414 | pb.update() 415 | t.value = "" 416 | t2.value = "" 417 | t.update() 418 | b.disabled = False 419 | b.update() 420 | 421 | b = ft.ElevatedButton("Download Playlist", width=200000, on_click=button_clicked) 422 | view = ft.Container( 423 | 424 | content = ft.Column( 425 | [ 426 | b, 427 | ft.Container( 428 | # image_src=img, 429 | # image_opacity= 0, 430 | # image_fit= ft.ImageFit.COVER, 431 | padding=10, 432 | content=ft.Column([ 433 | ft.Divider(opacity=0), 434 | t, 435 | pb, 436 | t2, 437 | ft.Divider(opacity=0)]), 438 | 439 | ) 440 | 441 | ],) 442 | ) 443 | return view 444 | 445 | 446 | class GestureDetector: 447 | def __init__(self): 448 | self.detector = ft.GestureDetector( 449 | on_pan_update=self.on_pan_update 450 | ) 451 | def on_pan_update(self,e): 452 | if e.delta_x<0: 453 | switch_to_sp_tab(e) 454 | elif e.delta_x>0: 455 | switch_to_yt_tab(e) 456 | def navigation_drawer(): 457 | spotify_client_id = ft.TextField(keyboard_type=ft.KeyboardType.TEXT) 458 | spotify_client_secret = ft.TextField(keyboard_type=ft.KeyboardType.TEXT) 459 | spotify_client_id.value = os.getenv('SPOTIPY_CLIENT_ID') 460 | spotify_client_secret.value = os.getenv('SPOTIPY_CLIENT_SECRET') 461 | def save_app_settings(e): 462 | try: 463 | env_str = "SPOTIPY_CLIENT_ID=" + spotify_client_id.value + "\nSPOTIPY_CLIENT_SECRET=" + spotify_client_secret.value 464 | with open(".env", "a+") as f: 465 | f.seek(0) # Move the cursor to the beginning of the file 466 | f.truncate() # Clear the file content 467 | f.write(env_str) 468 | except Exception as e: 469 | print(e) 470 | return "app settings update failed" 471 | return "app settings updated" 472 | def yt_page_launch(e): 473 | e.control.page.launch_url('https://youtu.be/vT43uBHq974') 474 | def petreon_page_launch(e): 475 | e.control.page.launch_url('https://www.patreon.com/c/Predacons') 476 | def github_page_launch(e): 477 | e.control.page.launch_url('https://github.com/shouryashashank/Trackster') 478 | def email_page_launch(e): 479 | e.control.page.launch_url('https://www.patreon.com/messages/ffd73e51aa264a61842c446763dbaff9?mode=campaign&tab=chats') 480 | def close_end_drawer(e): 481 | e.control.page.end_drawer = end_drawer 482 | end_drawer.open = False 483 | e.control.page.update() 484 | end_drawer = ft.NavigationDrawer([ 485 | ft.SafeArea( 486 | ft.Column( 487 | [ 488 | ft.Row( 489 | [ 490 | ft.Text(""), 491 | ft.IconButton(icon=ft.icons.CLOSE,on_click=close_end_drawer) 492 | ], 493 | alignment=ft.MainAxisAlignment.SPACE_BETWEEN 494 | ), 495 | ft.Text("Spotify client id:"), 496 | spotify_client_id, 497 | ft.Text("Spotify client secret:"), 498 | spotify_client_secret, 499 | ft.ElevatedButton("Save",on_click=save_app_settings), 500 | ft.TextButton("How To Get Spotify api api Keys",on_click=yt_page_launch), 501 | ft.TextButton("Contact support",on_click=email_page_launch), 502 | ft.TextButton("Get version with api key already added.",on_click=petreon_page_launch), 503 | ft.TextButton("Help me buy a new phone",on_click=petreon_page_launch), 504 | ft.TextButton("See source code",on_click=github_page_launch) 505 | 506 | ] 507 | ), 508 | minimum_padding= 10, 509 | ) 510 | ]) 511 | 512 | def open_end_drawer(e): 513 | e.control.page.end_drawer = end_drawer 514 | end_drawer.open = True 515 | e.control.page.update() 516 | 517 | return open_end_drawer 518 | 519 | 520 | def popup(page,text): 521 | return ft.AlertDialog( 522 | title=ft.Text(text), 523 | on_dismiss=lambda e: page.add(ft.Text("Non-modal dialog dismissed")), 524 | ) 525 | 526 | def drop_down(): 527 | 528 | return ft.Dropdown( 529 | label="Song Exist Action", 530 | hint_text="What to do when that song already exist in your directory?", 531 | options=[ 532 | ft.dropdown.Option("Replace all"), 533 | ft.dropdown.Option("Skip all"), 534 | ], 535 | autofocus=True, 536 | ) 537 | 538 | def app_bar(): 539 | view = ft.AppBar( 540 | title=ft.Text("Trackster"), 541 | actions=[ 542 | ft.IconButton(ft.icons.MENU, style=ft.ButtonStyle(padding=0),on_click=navigation_drawer()) 543 | ], 544 | bgcolor=ft.colors.with_opacity(0.04, ft.cupertino_colors.SYSTEM_BACKGROUND), 545 | ) 546 | return view 547 | 548 | def handle_nav_change(e): 549 | if e.control.selected_index == 0: 550 | switch_to_yt_tab(e) 551 | elif e.control.selected_index == 1: 552 | switch_to_sp_tab(e) 553 | elif e.control.selected_index == 2: 554 | switch_to_am_tab(e) 555 | elif e.control.selected_index == 3: 556 | switch_to_search_tab(e) 557 | def nav_bar(): 558 | view = ft.NavigationBar( 559 | destinations=[ 560 | ft.NavigationBarDestination(icon=ft.icons.ONDEMAND_VIDEO_ROUNDED, label="Youtube"), 561 | ft.NavigationBarDestination(icon=ft.icons.MUSIC_NOTE, label="Spotify"), 562 | ft.NavigationBarDestination(icon=ft.icons.APPLE_OUTLINED, label="Apple Music"), 563 | ft.NavigationBarDestination(icon=ft.icons.SEARCH, label="Search"), 564 | ], 565 | on_change=handle_nav_change, 566 | border=ft.Border( 567 | top=ft.BorderSide(color=ft.cupertino_colors.SYSTEM_GREY2, width=0) 568 | ), 569 | ) 570 | return view 571 | 572 | 573 | class FolderPicker(ft.Row): 574 | def build(self): 575 | view = ft.Row( 576 | [ 577 | ft.ElevatedButton( 578 | "Select Folder", 579 | icon=ft.icons.FOLDER_OPEN, 580 | on_click=lambda _: get_directory_dialog.get_directory_path() 581 | ), 582 | directory_path, 583 | # ft.Text(value="Select Output Direcotry to save the playlist", italic=False, selectable=False, style='labelSmall', ), 584 | ] 585 | ) 586 | return view 587 | def switch_to_yt_tab(e): 588 | e.control.page.title= "Youtube" 589 | set_theme(e,"Red") 590 | e.control.page.youtube_tab.visible = True 591 | e.control.page.spotify_tab.visible = False 592 | e.control.page.apple_music_tab.visible = False 593 | e.control.page.search_tab.visible = False 594 | e.control.page.navigation_bar.selected_index = 0 595 | e.control.page.update() 596 | 597 | def switch_to_sp_tab(e): 598 | e.control.page.title= "Spotify" 599 | set_theme(e,"Green") 600 | e.control.page.youtube_tab.visible = False 601 | e.control.page.spotify_tab.visible = True 602 | e.control.page.apple_music_tab.visible = False 603 | e.control.page.search_tab.visible = False 604 | e.control.page.navigation_bar.selected_index = 1 605 | e.control.page.update() 606 | 607 | def switch_to_am_tab(e): 608 | e.control.page.title= "Apple Music" 609 | set_theme(e,"Blue") 610 | e.control.page.youtube_tab.visible = False 611 | e.control.page.spotify_tab.visible = False 612 | e.control.page.apple_music_tab.visible = True 613 | e.control.page.search_tab.visible = False 614 | e.control.page.navigation_bar.selected_index = 2 615 | e.control.page.update() 616 | 617 | def switch_to_search_tab(e): 618 | e.control.page.title = "Search" 619 | set_theme(e, "Purple") 620 | e.control.page.youtube_tab.visible = False 621 | e.control.page.spotify_tab.visible = False 622 | e.control.page.apple_music_tab.visible = False 623 | e.control.page.search_tab.visible = True 624 | e.control.page.navigation_bar.selected_index = 3 625 | e.control.page.update() 626 | 627 | def get_track_info(track_url, sp, max_retries=3, initial_timeout=1): 628 | """ 629 | Get track metadata from Spotify with retry logic for timeouts. 630 | 631 | Args: 632 | track_url (str): Spotify track URL 633 | sp: Authenticated Spotipy client 634 | max_retries (int): Maximum number of retry attempts 635 | initial_timeout (float): Initial timeout between retries in seconds (will exponentially increase) 636 | 637 | Returns: 638 | dict: Track metadata or None if all attempts fail 639 | """ 640 | last_exception = None 641 | 642 | for attempt in range(max_retries + 1): # +1 for the initial attempt 643 | try: 644 | track = sp.track(track_url) 645 | isrc = track["external_ids"].get("isrc") if track.get("external_ids") else None 646 | 647 | track_metadata = { 648 | "artist_name": track["artists"][0]["name"], 649 | "track_title": track["name"], 650 | "track_number": track["track_number"], 651 | "isrc": isrc, 652 | "album_art": track["album"]["images"][1]["url"], 653 | "album_name": track["album"]["name"], 654 | "release_date": track["album"]["release_date"], 655 | "artists": [artist["name"] for artist in track["artists"]], 656 | } 657 | 658 | return track_metadata 659 | 660 | except Exception as e: 661 | last_exception = e 662 | if attempt < max_retries: 663 | wait_time = initial_timeout * (2 ** attempt) # Exponential backoff 664 | print(f"Attempt {attempt + 1} failed. Retrying in {wait_time} seconds... Error: {str(e)}") 665 | time.sleep(wait_time) 666 | continue 667 | 668 | # If we get here, all attempts failed 669 | print(f"Failed to get track info after {max_retries + 1} attempts. Last error: {str(last_exception)}") 670 | return None 671 | 672 | def find_youtube(query): 673 | query = query.replace("é", "e") 674 | query = query.replace("’", "") 675 | query = query.replace("æ", "ae") 676 | query = query.replace("ñ", "n") 677 | query = query.replace("–", "+") 678 | query = query.replace("‘", "") 679 | query = query.replace("ú", "u") 680 | 681 | 682 | phrase = query.replace(" ", "+") 683 | search_link = "https://www.youtube.com/results?search_query=" + phrase 684 | count = 0 685 | while count < 5: 686 | try: 687 | search_link = str(URL(search_link)) 688 | response = urllib.request.urlopen(search_link) 689 | break 690 | except: 691 | count += 1 692 | else: 693 | raise ValueError("Please check your internet connection and try again later.") 694 | 695 | 696 | search_results = re.findall(r"watch\?v=(\S{11})", response.read().decode()) 697 | first_vid = "https://www.youtube.com/watch?v=" + search_results[0] 698 | 699 | return first_vid 700 | 701 | def get_playlist_info(sp_playlist,sp): 702 | res = requests.get(sp_playlist) 703 | if res.status_code != 200: 704 | raise ValueError("Invalid Spotify playlist URL") 705 | pl = sp.playlist(sp_playlist) 706 | if not pl["public"]: 707 | raise ValueError( 708 | "Can't download private playlists. Change your playlist's state to public." 709 | ) 710 | playlist = sp.playlist_tracks(sp_playlist) 711 | 712 | tracks_item = playlist['items'] 713 | 714 | while playlist['next']: 715 | playlist = sp.next(playlist) 716 | tracks_item.extend(playlist['items']) 717 | 718 | tracks = [item["track"] for item in tracks_item] 719 | tracks_info = [] 720 | track_id = [] 721 | # load tracks_id from synced.txt 722 | if os.path.exists("synced.txt"): 723 | with open("synced.txt", "r") as f: 724 | track_id = f.read().splitlines() 725 | updated_tracks = [] 726 | try: 727 | for track in tqdm(tracks): 728 | # check if the track['id'] is not none 729 | if track["id"] is None: 730 | continue 731 | 732 | if track["id"] in track_id: 733 | continue 734 | 735 | updated_tracks.append(track["id"]) 736 | 737 | track_url = f"https://open.spotify.com/track/{track['id']}" 738 | track_info = get_track_info(track_url,sp) 739 | # make a progress bar 740 | 741 | tracks_info.append(track_info) 742 | except Exception as e: 743 | print(f"Failed to get track info for {track['name']} due to: {e}") 744 | # save the updated tracks_id to synced_updated.txt 745 | try: 746 | with open("synced_updated.txt", "w") as f: 747 | f.write("\n".join(updated_tracks)) 748 | except Exception as e: 749 | print(f"Failed to save updated tracks: {e}") 750 | return tracks_info 751 | 752 | def get_album_info(sp_album,sp): 753 | res = requests.get(sp_album) 754 | if res.status_code != 200: 755 | raise ValueError("Invalid Spotify playlist URL") 756 | # pl = sp.album(sp_album) 757 | 758 | playlist = sp.album_tracks(sp_album) 759 | 760 | tracks_item = playlist['items'] 761 | 762 | while playlist['next']: 763 | playlist = sp.next(playlist) 764 | tracks_item.extend(playlist['items']) 765 | 766 | # tracks = [item["track"] for item in tracks_item] 767 | tracks_info = [] 768 | track_id = [] 769 | # load tracks_id from synced.txt 770 | if os.path.exists("synced.txt"): 771 | with open("synced.txt", "r") as f: 772 | track_id = f.read().splitlines() 773 | updated_tracks = [] 774 | def process_track(track): 775 | updated_tracks.append(track["id"]) 776 | if track["id"] in track_id: 777 | return None 778 | track_url = f"https://open.spotify.com/track/{track['id']}" 779 | return get_track_info(track_url, sp) 780 | 781 | with ThreadPoolExecutor() as executor: 782 | results = list(tqdm(executor.map(process_track, tracks_item), total=len(tracks_item))) 783 | 784 | tracks_info.extend(filter(None, results)) 785 | # make a progress bar 786 | 787 | # save the updated tracks_id to synced_updated.txt 788 | with open("synced_updated.txt", "w") as f: 789 | f.write("\n".join(updated_tracks)) 790 | return tracks_info 791 | 792 | def main(page: ft.Page): 793 | page.adaptive = True 794 | page.appbar = app_bar() 795 | page.navigation_bar = nav_bar() 796 | # hide all dialogs in overlay 797 | folder_picker = FolderPicker() 798 | url = ft.TextField(keyboard_type=ft.KeyboardType.TEXT) 799 | pb = ft.ProgressBar() 800 | c1 = ft.Checkbox(label="Download only failed songs", value=False) 801 | c2 = ft.Checkbox(label="Download high quality audio", value=False) 802 | # c2 = ft.Checkbox(label="Download high quality audio (🙏 please get it from petreon or build from source to eneble this)", value=False,disabled=True) 803 | # def switch_to_yt_tab(e): 804 | # page.title= "Youtube" 805 | # youtube_tab.visible = True 806 | # spotify_tab.visible = False 807 | # page.navigation_bar.selected_index = 0 808 | # page.update 809 | 810 | # def switch_to_sp_tab(e): 811 | # page.title= "Spotify" 812 | # youtube_tab.visible = False 813 | # spotify_tab.visible = True 814 | # page.navigation_bar.selected_index = 1 815 | # page.update 816 | page.theme = ft.Theme(color_scheme_seed="Red") 817 | gesture_detector = GestureDetector() 818 | dd = ft.Dropdown( 819 | label="Song Exist Action", 820 | hint_text="What to do when that song already exist in your directory?", 821 | options=[ 822 | ft.dropdown.Option("Replace all"), 823 | ft.dropdown.Option("Skip all"), 824 | ], 825 | autofocus=True, 826 | ) 827 | # link = "https://www.youtube.com/watch?v=uelHwf8o7_U&list=PLGyF7r13ifSqeOxzefZfjiSgSoBK2W4fQ" 828 | # exists_action ="Replace all" 829 | def downloader(): 830 | try: 831 | t = ft.Text(value="") 832 | t2 = ft.Text(value = "0") 833 | pb = ft.ProgressBar(value=0) 834 | def button_clicked(e): 835 | link = url.value 836 | exists_action = dd.value 837 | t.value = "Downloading" 838 | t.update() 839 | b.disabled = True 840 | b.update() 841 | custom_labels = { 842 | "Replace all": "RA", 843 | "Skip all": "SA", 844 | "Determine while downloading from CLI": "", 845 | } 846 | global file_exists_action 847 | file_exists_action = custom_labels[exists_action] 848 | use_spotify_for_metadata = True 849 | try: 850 | load_dotenv() 851 | SPOTIPY_CLIENT_ID = os.getenv('SPOTIPY_CLIENT_ID') 852 | SPOTIPY_CLIENT_SECRET = os.getenv('SPOTIPY_CLIENT_SECRET') 853 | client_credentials_manager = SpotifyClientCredentials( 854 | client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET 855 | ) 856 | sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) 857 | except Exception as e: 858 | use_spotify_for_metadata = False 859 | print(f"Failed to connect to Spotify API: {e}") 860 | print("Continuing without Spotify API, some song metadata will not be added") 861 | exception_popup = popup(page,f"⚠️ Failed to connect to Spotify API: {e} . Continuing without Spotify API, some song metadata will not be added") 862 | page.open(exception_popup) 863 | # link = input("Enter YouTube Playlist URL: ✨") 864 | 865 | yt_playlist = Playlist(link) 866 | 867 | 868 | 869 | totalVideoCount = len(yt_playlist.videos) 870 | print("Total videos in playlist: 🎦", totalVideoCount) 871 | 872 | for index, video in enumerate(yt_playlist.videos): 873 | try: 874 | if c1.value: 875 | if os.path.exists("failed_downloads.txt"): 876 | with open("failed_downloads.txt", "r") as f: 877 | failed_songs = f.read().splitlines() 878 | if video.title not in failed_songs: 879 | continue 880 | print("Downloading: "+video.title) 881 | t2.value = f"{index+1}/{totalVideoCount}" 882 | pb.value = ((index+1)/totalVideoCount) 883 | 884 | view.update() 885 | t2.update() 886 | pb.update() 887 | 888 | audio = download_yt(video,video.title) 889 | if audio: 890 | if(use_spotify_for_metadata): 891 | try: 892 | track_url = search_spotify(f"{video.author} {video.title}",sp) 893 | except Exception as e: 894 | print(e) 895 | track_url = None 896 | if not track_url: 897 | track_info = get_track_info_youtube(video) 898 | else: 899 | track_info = get_track_info_spotify(track_url,sp) 900 | else: 901 | track_info = get_track_info_youtube(video) 902 | 903 | set_metadata(track_info, audio,"") 904 | os.replace(audio, f"{music_folder_path}{os.path.basename(audio)}") 905 | except Exception as e: 906 | print(f"Failed to download {video.title} due to: {e}") 907 | with open("failed_downloads.txt", "a") as f: 908 | f.write(f"{video.title}\n") 909 | continue 910 | t.value = "Downloaded" 911 | t2.value = "" 912 | t.update() 913 | b.disabled = False 914 | b.update() 915 | print("All videos downloaded successfully!") 916 | b = ft.ElevatedButton("Download Playlist", width=200000, on_click=button_clicked) 917 | view = ft.Container( 918 | 919 | content = ft.Column( 920 | [ 921 | b, 922 | ft.Container( 923 | # image_src=img, 924 | # image_opacity= 0, 925 | # image_fit= ft.ImageFit.COVER, 926 | padding=10, 927 | content=ft.Column([ 928 | ft.Divider(opacity=0), 929 | t, 930 | pb, 931 | t2, 932 | ft.Divider(opacity=0)]), 933 | 934 | ) 935 | 936 | ],) 937 | ) 938 | return view 939 | # return "All videos downloaded successfully!" 940 | except Exception as e: 941 | print(e) 942 | exception_popup = popup(page,f"⚠️ Failed to download. make sure all the options are properly selected, and the link is correct. restart and try again") 943 | page.open(exception_popup) 944 | 945 | def downloader_spotify(): 946 | t = ft.Text(value="") 947 | t2 = ft.Text(value = "0") 948 | pb = ft.ProgressBar(value=0) 949 | def button_clicked(e): 950 | print("Downloading: here you will se a progress bar. if that progress bar is stuck that means, spotify is rate limiting you. wait for a while and try again or download the 'no spotify key' version. for now there is no work around this. sorry for the inconvenience") 951 | link = url.value 952 | exists_action = dd.value 953 | t.value = "Fetching Playlist meta data (dont freak out if it takes a while 😅 it will take about a minute for 300 songs)" 954 | t.update() 955 | b.disabled = True 956 | b.update() 957 | try: 958 | custom_labels = { 959 | "Replace all": "RA", 960 | "Skip all": "SA", 961 | "Determine while downloading from CLI": "", 962 | } 963 | global file_exists_action 964 | file_exists_action = custom_labels[exists_action] 965 | use_spotify_for_metadata = True 966 | try: 967 | load_dotenv() 968 | SPOTIPY_CLIENT_ID = os.getenv('SPOTIPY_CLIENT_ID') 969 | SPOTIPY_CLIENT_SECRET = os.getenv('SPOTIPY_CLIENT_SECRET') 970 | client_credentials_manager = SpotifyClientCredentials( 971 | client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET 972 | ) 973 | sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) 974 | except Exception as e: 975 | use_spotify_for_metadata = False 976 | print(f"Failed to connect to Spotify API: {e}") 977 | print("Continuing without Spotify API, some song metadata will not be added") 978 | exception_popup = popup(page,f"⚠️ Failed to connect to Spotify API: {e} . Continuing without Spotify API, some song metadata will not be added") 979 | page.open(exception_popup) 980 | # link = input("Enter YouTube Playlist URL: ✨") 981 | 982 | if "track" in link: 983 | songs = [get_track_info(link,sp)] 984 | elif "playlist" in link: 985 | songs = get_playlist_info(link,sp) 986 | else: 987 | songs = get_album_info(link,sp) 988 | # pickle the songs list 989 | # with open("songs.pkl", "wb") as f: 990 | # pickle.dump(songs, f) 991 | # with open("songs.pkl", "rb") as f: 992 | # songs = pickle.load(f) 993 | t.value = "Starting Download" 994 | t.update() 995 | downloaded = 0 996 | song_name_list = [] 997 | if os.path.exists("song_names.txt"): 998 | if input("only download the songs that are not already downloaded [y/n]: ").strip() == "y": 999 | with open("song_names.txt", "r") as f: 1000 | song_name_list = f.read().splitlines() 1001 | # check if downloaded.txt exists 1002 | # if os.path.exists("downloaded.txt"): 1003 | # if input("Resume download? [y/n]: ").strip() == "y": 1004 | # with open("downloaded.txt", "r") as f: 1005 | # downloaded = int(f.read()) 1006 | totalVideoCount = len(songs) 1007 | for i, track_info in enumerate(songs): 1008 | try: 1009 | # check if the song is already downloaded at f"{music_folder_path}{search_term}.mp3" 1010 | if dd.value == "Skip all": 1011 | if os.path.exists(f"{music_folder_path}{track_info['track_title']}.mp3"): 1012 | print("Skipping: "+track_info["track_title"]) 1013 | continue 1014 | if c1.value: 1015 | if os.path.exists("failed_downloads.txt"): 1016 | with open("failed_downloads.txt", "r", encoding="utf-8") as f: 1017 | failed_songs = f.read().splitlines() 1018 | if track_info["track_title"] not in failed_songs: 1019 | continue 1020 | print("Downloading: "+track_info["track_title"]) 1021 | t2.value = f"{i+1}/{totalVideoCount}" 1022 | pb.value = ((i+1)/totalVideoCount) 1023 | t.value = "Downloading: "+track_info["track_title"] 1024 | t.update() 1025 | view.update() 1026 | t2.update() 1027 | pb.update() 1028 | if track_info["track_title"] in song_name_list: 1029 | continue 1030 | if downloaded > i: 1031 | continue 1032 | search_term = f"{track_info['artist_name']} {track_info['track_title']} audio" 1033 | hq_search_term = f"{track_info['track_title']} {track_info['artist_name']} {track_info['album_name']}" 1034 | lyrics = "" 1035 | if c2.value: 1036 | song = download_high_quality(hq_search_term) 1037 | if song == "No songs found for the query.": 1038 | try: 1039 | print("No songs found for the query in high quality song server." , search_term) 1040 | print("Trying to download from youtube") 1041 | video_link = find_youtube(search_term) 1042 | yt = YouTube(video_link) 1043 | audio = download_yt(yt,search_term) 1044 | except Exception as e: 1045 | print("No songs found for the query in high quality song server." , search_term) 1046 | tt = track_info["track_title"] 1047 | with open("failed_downloads.txt", "a", encoding="utf-8") as f: 1048 | f.write(f"{tt}\n") 1049 | print("Skipping... adding to failed_downloads.txt redownload with low quality in next run" ) 1050 | continue 1051 | else: 1052 | artist = song['song'] + " " + song['primary_artists'] + " " + song['album'] 1053 | diff_ratio = difflib.SequenceMatcher(None, artist.lower(), (track_info['track_title'] + " " +track_info["artist_name"]+ " " +track_info["album_name"]).lower()).ratio() 1054 | # compare the artist name from the song and the artist name from the track_info 1055 | if (diff_ratio<0.7): 1056 | try: 1057 | print("songs found for the query in high quality song server. very different from the one in spotify" , search_term) 1058 | print("Trying to download from youtube") 1059 | video_link = find_youtube(search_term) 1060 | yt = YouTube(video_link) 1061 | audio = download_yt(yt,search_term) 1062 | except Exception as e: 1063 | print("No songs found for the query in high quality song server." , search_term) 1064 | tt = track_info["track_title"] 1065 | with open("failed_downloads.txt", "a", encoding="utf-8") as f: 1066 | f.write(f"{tt}\n") 1067 | print("Skipping... adding to failed_downloads.txt redownload with low quality in next run" ) 1068 | continue 1069 | 1070 | elif (diff_ratio<0.9): 1071 | print("Artist name mismatch. Skipping...") 1072 | tt = track_info["track_title"] 1073 | aa = track_info["artist_name"] 1074 | with open("mismatched_downloads.txt", "a", encoding="utf-8") as f: 1075 | f.write(f"{tt} || Orignal artist : {aa} || Downloaded artist: {artist}\n") 1076 | continue 1077 | audio = song["mp3"] 1078 | lyrics = song["lyrics"] 1079 | else: 1080 | video_link = find_youtube(search_term) 1081 | yt = YouTube(video_link) 1082 | audio = download_yt(yt,search_term) 1083 | if audio: 1084 | # track_info["track_number"] = downloaded + 1 1085 | set_metadata(track_info, audio,lyrics) 1086 | sanitized_title = sanitize_filename(track_info['track_title']) 1087 | destination_path = os.path.join(music_folder_path, f"{sanitized_title}.mp3") 1088 | os.replace(audio, destination_path) 1089 | downloaded += 1 1090 | # save the downloaded count to a file 1091 | with open("downloaded.txt", "w") as f: 1092 | f.write(str(downloaded)) 1093 | else: 1094 | print("File exists. Skipping...") 1095 | except Exception as e: 1096 | tt = track_info["track_title"] 1097 | print(f"Failed to download {tt} due to: {e}") 1098 | with open("failed_downloads.txt", "a", encoding="utf-8") as f: 1099 | f.write(f"{tt}\n") 1100 | continue 1101 | t.value = "Downloaded" 1102 | t2.value = "" 1103 | t.update() 1104 | b.disabled = False 1105 | b.update() 1106 | print("All songs downloaded successfully!") 1107 | print("Few more steps to go. 🚀") 1108 | print("1. Open the downloaded folder and check if all the songs are downloaded.") 1109 | print("2. open mismatched_downloads.txt and check if any songs are mismatched. most of them should be fine but still manually check the songs. if it is not the song you wanted, delete the song from the folder.") 1110 | print("3. restart the app and download again but with high quality audio turned off. this will download the songs from youtube. make sure to select skip all in the song exist action dropdown.") 1111 | print("4. open failed_downloads.txt and download the songs that are failed to download.") 1112 | completion_popup = popup(page,"All songs downloaded successfully!\n Few more steps to go. 🚀 \n1. Open the downloaded folder and check if all the songs are downloaded. \n2. open mismatched_downloads.txt and check if any songs are mismatched. most of them should be fine but still manually check the songs. if it is not the song you wanted, delete the song from the folder.\n3. restart the app and download again but with high quality audio turned off. this will download the songs from youtube. make sure to select skip all in the song exist action dropdown.") 1113 | page.open(completion_popup) 1114 | except Exception as e: 1115 | print(e) 1116 | exception_popup = popup(page,f"⚠️ Failed to download. make sure all the options are properly selected, and the link is correct. restart and try again ({e})") 1117 | page.open(exception_popup) 1118 | b = ft.ElevatedButton("Download Playlist", width=200000, on_click=button_clicked) 1119 | view = ft.Container( 1120 | 1121 | content = ft.Column( 1122 | [ 1123 | b, 1124 | ft.Container( 1125 | # image_src=img, 1126 | # image_opacity= 0, 1127 | # image_fit= ft.ImageFit.COVER, 1128 | padding=10, 1129 | content=ft.Column([ 1130 | ft.Divider(opacity=0), 1131 | t, 1132 | pb, 1133 | t2, 1134 | ft.Divider(opacity=0)]), 1135 | 1136 | ) 1137 | 1138 | ],) 1139 | ) 1140 | return view 1141 | 1142 | def downloader_apple_music(): 1143 | try: 1144 | t = ft.Text(value="") 1145 | t2 = ft.Text(value = "0") 1146 | pb = ft.ProgressBar(value=0) 1147 | def button_clicked(e): 1148 | 1149 | link = url.value 1150 | exists_action = dd.value 1151 | t.value = "Fetching Playlist meta data (dont freak out if it takes a while 😅 it will take about a minute for 100 songs)" 1152 | t.update() 1153 | b.disabled = True 1154 | b.update() 1155 | custom_labels = { 1156 | "Replace all": "RA", 1157 | "Skip all": "SA", 1158 | "Determine while downloading from CLI": "", 1159 | } 1160 | global file_exists_action 1161 | file_exists_action = custom_labels[exists_action] 1162 | use_spotify_for_metadata = True 1163 | try: 1164 | load_dotenv() 1165 | SPOTIPY_CLIENT_ID = os.getenv('SPOTIPY_CLIENT_ID') 1166 | SPOTIPY_CLIENT_SECRET = os.getenv('SPOTIPY_CLIENT_SECRET') 1167 | client_credentials_manager = SpotifyClientCredentials( 1168 | client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET 1169 | ) 1170 | sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) 1171 | except Exception as e: 1172 | use_spotify_for_metadata = False 1173 | print(f"Failed to connect to Spotify API: {e}") 1174 | print("Continuing without Spotify API, some song metadata will not be added") 1175 | exception_popup = popup(page,f"⚠️ Failed to connect to Spotify API: {e} . Continuing without Spotify API, some song metadata will not be added") 1176 | page.open(exception_popup) 1177 | # link = input("Enter YouTube Playlist URL: ✨") 1178 | 1179 | am_playlist = apple.get_playlist(link) 1180 | 1181 | 1182 | 1183 | totalVideoCount = len(am_playlist) 1184 | print("Total songs in playlist:", totalVideoCount) 1185 | 1186 | for index, song in enumerate(am_playlist): 1187 | try: 1188 | # check if the song is already downloaded at f"{music_folder_path}{search_term}.mp3" 1189 | if dd.value == "Skip all": 1190 | if os.path.exists(f"{music_folder_path}{song}.mp3"): 1191 | print("Skipping: "+song) 1192 | continue 1193 | if c1.value: 1194 | if os.path.exists("failed_downloads.txt"): 1195 | with open("failed_downloads.txt", "r") as f: 1196 | failed_songs = f.read().splitlines() 1197 | if song not in failed_songs: 1198 | continue 1199 | print("Downloading: "+song) 1200 | t2.value = f"{index+1}/{totalVideoCount}" 1201 | pb.value = ((index+1)/totalVideoCount) 1202 | 1203 | view.update() 1204 | t2.update() 1205 | pb.update() 1206 | lyrics = "" 1207 | if c2.value: 1208 | song_js = download_high_quality(song) 1209 | if song_js == "No songs found for the query.": 1210 | try: 1211 | print("No songs found for the query in high quality song server." , song) 1212 | print("Trying to download from youtube") 1213 | video_link = find_youtube(song) 1214 | yt = YouTube(video_link) 1215 | audio = download_yt(yt,song) 1216 | except Exception as e: 1217 | print("No songs found for the query in high quality song server." , song) 1218 | with open("failed_downloads.txt", "a", encoding="utf-8") as f: 1219 | f.write(f"{song}\n") 1220 | print("Skipping... adding to failed_downloads.txt redownload with low quality in next run" ) 1221 | continue 1222 | else: 1223 | audio = song_js["mp3"] 1224 | lyrics = song_js["lyrics"] 1225 | else: 1226 | video_link = find_youtube(song) 1227 | yt = YouTube(video_link) 1228 | audio = download_yt(yt,song) 1229 | if audio: 1230 | if(use_spotify_for_metadata): 1231 | try: 1232 | spotify_search_term = song.replace(" by", "").replace(" audio", "") 1233 | track_url = search_spotify(spotify_search_term,sp) 1234 | except Exception as e: 1235 | print(e) 1236 | track_url = None 1237 | if not track_url: 1238 | track_info = get_track_info_youtube(yt) 1239 | else: 1240 | track_info = get_track_info_spotify(track_url,sp) 1241 | else: 1242 | track_info = get_track_info_youtube(yt) 1243 | 1244 | set_metadata(track_info, audio,lyrics) 1245 | os.replace(audio, f"{music_folder_path}{os.path.basename(audio)}") 1246 | except Exception as e: 1247 | print(f"Failed to download {song} due to: {e}") 1248 | with open("failed_downloads.txt", "a") as f: 1249 | f.write(f"{song}\n") 1250 | continue 1251 | t.value = "Downloaded" 1252 | t2.value = "" 1253 | t.update() 1254 | b.disabled = False 1255 | b.update() 1256 | print("All songs downloaded successfully!") 1257 | print("Few more steps to go. 🚀") 1258 | print("1. Open the downloaded folder and check if all the songs are downloaded.") 1259 | print("2. some songs downloaded from the high quality audio server might not be the song you wanted. please check the songs manually and delete the songs that are not the song you wanted.") 1260 | print("3. restart the app and download again but with high quality audio turned off. this will download the songs from youtube. make sure to select skip all in the song exist action dropdown.") 1261 | print("4. open failed_downloads.txt and download the songs that are failed to download.") 1262 | completion_popup = popup(page,"All songs downloaded successfully!\n Few more steps to go. 🚀 \n1. Open the downloaded folder and check if all the songs are downloaded. \n2. some songs downloaded from the high quality audio server might not be the song you wanted. please check the songs manually and delete the songs that are not the song you wanted.\n3. restart the app and download again but with high quality audio turned off. this will download the songs from youtube. make sure to select skip all in the song exist action dropdown.") 1263 | page.open(completion_popup) 1264 | b = ft.ElevatedButton("Download Playlist", width=200000, on_click=button_clicked) 1265 | view = ft.Container( 1266 | 1267 | content = ft.Column( 1268 | [ 1269 | b, 1270 | ft.Container( 1271 | # image_src=img, 1272 | # image_opacity= 0, 1273 | # image_fit= ft.ImageFit.COVER, 1274 | padding=10, 1275 | content=ft.Column([ 1276 | ft.Divider(opacity=0), 1277 | t, 1278 | pb, 1279 | t2, 1280 | ft.Divider(opacity=0)]), 1281 | 1282 | ) 1283 | 1284 | ],) 1285 | ) 1286 | return view 1287 | # return "All videos downloaded successfully!" 1288 | except Exception as e: 1289 | print(e) 1290 | exception_popup = popup(page,f"⚠️ Failed to download. make sure all the options are properly selected, and the link is correct. restart and try again") 1291 | page.open(exception_popup) 1292 | 1293 | youtube_tab = ft.Container( 1294 | ft.SafeArea( 1295 | content=ft.Column( 1296 | [ 1297 | ft.Divider(opacity=0, height= 20), 1298 | folder_picker, 1299 | ft.Divider(opacity=0, height= 20), 1300 | ft.Text("Enter Youtube playlist url:"), 1301 | url, 1302 | ft.Divider(opacity=0), 1303 | dd, 1304 | ft.Divider(opacity=0), 1305 | # ft.ElevatedButton(text="Download Playlist",width=200000), 1306 | c1, 1307 | ft.Divider(opacity=0), 1308 | downloader(), 1309 | # ft.FilledButton("sp",on_click=switch_to_sp_tab) 1310 | gesture_detector.detector, 1311 | 1312 | ] 1313 | ) 1314 | ), 1315 | visible= True 1316 | ) 1317 | 1318 | spotify_tab = ft.Container( 1319 | ft.SafeArea( 1320 | content=ft.Column( 1321 | [ 1322 | ft.Divider(opacity=0, height= 20), 1323 | folder_picker, 1324 | ft.Divider(opacity=0, height= 20), 1325 | ft.Text("Enter Spotify playlist or album url:"), 1326 | url, 1327 | ft.Divider(opacity=0), 1328 | dd, 1329 | ft.Divider(opacity=0), 1330 | ft.Row([c1,c2]), 1331 | ft.Divider(opacity=0), 1332 | # ft.ElevatedButton(text="Download Playlist",width=200000), 1333 | downloader_spotify(), 1334 | # ft.FilledButton("yt",on_click=switch_to_yt_tab) 1335 | gesture_detector.detector, 1336 | ] 1337 | ) 1338 | ), 1339 | visible= False 1340 | ) 1341 | apple_music_tab = ft.Container( 1342 | ft.SafeArea( 1343 | content=ft.Column( 1344 | [ 1345 | ft.Divider(opacity=0, height= 20), 1346 | folder_picker, 1347 | ft.Divider(opacity=0, height= 20), 1348 | ft.Text("Enter Apple Music playlist or album url:"), 1349 | url, 1350 | ft.Divider(opacity=0), 1351 | dd, 1352 | ft.Divider(opacity=0), 1353 | ft.Row([c1,c2]), 1354 | ft.Divider(opacity=0), 1355 | # ft.ElevatedButton(text="Download Playlist",width=200000), 1356 | downloader_apple_music(), 1357 | # ft.FilledButton("yt",on_click=switch_to_yt_tab) 1358 | gesture_detector.detector, 1359 | ] 1360 | ) 1361 | ), 1362 | visible= False 1363 | ) 1364 | 1365 | # --- Search tab: allows searching artist/album and batch downloading --- 1366 | search_query = ft.TextField(keyboard_type=ft.KeyboardType.TEXT, width=800, hint_text="Type artist or album and press Search") 1367 | # Dropdown to select one candidate from topresult, artists and albums 1368 | search_candidates_dropdown = ft.Dropdown(label="Select result", width=800, options=[], on_change=lambda e: None) 1369 | # Show a preview (image + title) for the selected candidate 1370 | search_result_title = ft.Text("", size=16) 1371 | search_result_image = ft.Image(src="", width=100, height=100) 1372 | search_result_box = ft.Row([search_result_image, ft.Column([search_result_title])]) 1373 | search_progress = ft.ProgressBar(value=0) 1374 | 1375 | def perform_search(e): 1376 | q = search_query.value.strip() 1377 | if not q: 1378 | return 1379 | s = Search() 1380 | try: 1381 | res = s.search(q) 1382 | except Exception as err: 1383 | print(f"Search failed: {err}") 1384 | res = None 1385 | # clear previous 1386 | search_result_title.value = "" 1387 | search_result_image.src = "" 1388 | search_result_title.update() 1389 | search_result_image.update() 1390 | if not res or res == "not found": 1391 | search_result_title.value = "No result" 1392 | search_result_title.update() 1393 | search_result_image.update() 1394 | # clear dropdown 1395 | search_candidates_dropdown.options = [] 1396 | search_candidates_dropdown.update() 1397 | e.control.page.update() 1398 | return 1399 | 1400 | # Build a flat list of candidates with labels and keep full items in a map 1401 | candidates = [] 1402 | candidates_map = {} 1403 | idx = 0 1404 | if res.get('topresult'): 1405 | item = res['topresult'] 1406 | label = f"Top: {item.get('title') or item.get('name') or item.get('perma_url','')[:40]}" 1407 | key = f"c_{idx}" 1408 | candidates.append(ft.dropdown.Option(key=key, text=label)) 1409 | candidates_map[key] = item 1410 | idx += 1 1411 | 1412 | for a in res.get('artists', []): 1413 | label = f"Artist: {a.get('title') or a.get('name') or a.get('perma_url','')[:40]}" 1414 | key = f"c_{idx}" 1415 | candidates.append(ft.dropdown.Option(key=key, text=label)) 1416 | candidates_map[key] = a 1417 | idx += 1 1418 | 1419 | for al in res.get('albums', []): 1420 | label = f"Album: {al.get('title') or al.get('name') or al.get('perma_url','')[:40]}" 1421 | key = f"c_{idx}" 1422 | candidates.append(ft.dropdown.Option(key=key, text=label)) 1423 | candidates_map[key] = al 1424 | idx += 1 1425 | 1426 | # populate dropdown 1427 | search_candidates_dropdown.options = candidates 1428 | search_candidates_dropdown.value = candidates[0].key if candidates else None 1429 | # save map on page for download 1430 | e.control.page._search_candidates_map = candidates_map 1431 | 1432 | # update preview to first candidate 1433 | if candidates: 1434 | sel_key = search_candidates_dropdown.value 1435 | sel_item = candidates_map.get(sel_key) 1436 | title = sel_item.get('title') or sel_item.get('name') or '' 1437 | img = sel_item.get('image') or sel_item.get('album_art') or '' 1438 | search_result_title.value = title + f" ({sel_item.get('type','')})" 1439 | search_result_image.src = img 1440 | else: 1441 | search_result_title.value = "No result" 1442 | search_result_image.src = '' 1443 | 1444 | search_candidates_dropdown.update() 1445 | search_result_title.update() 1446 | search_result_image.update() 1447 | e.control.page.update() 1448 | 1449 | # update preview when user selects different candidate 1450 | def candidate_changed(e): 1451 | sel_key = e.control.value 1452 | candidates_map = getattr(e.control.page, '_search_candidates_map', {}) 1453 | sel_item = candidates_map.get(sel_key) 1454 | if not sel_item: 1455 | search_result_title.value = "No result" 1456 | search_result_image.src = "" 1457 | else: 1458 | title = sel_item.get('title') or sel_item.get('name') or '' 1459 | img = sel_item.get('image') or sel_item.get('album_art') or '' 1460 | search_result_title.value = title + f" ({sel_item.get('type','')})" 1461 | search_result_image.src = img 1462 | search_result_title.update() 1463 | search_result_image.update() 1464 | e.control.page.update() 1465 | 1466 | # wire dropdown change to handler 1467 | search_candidates_dropdown.on_change = candidate_changed 1468 | 1469 | def start_download(e): 1470 | # read selected candidate 1471 | sel_key = search_candidates_dropdown.value 1472 | candidates_map = getattr(e.control.page, '_search_candidates_map', {}) 1473 | sel = candidates_map.get(sel_key) 1474 | if not sel: 1475 | print("Nothing selected to download") 1476 | return 1477 | 1478 | async def run_download(): 1479 | s = Search() 1480 | # decide artist or album or single song 1481 | typ = sel.get('type') 1482 | if typ == 'artist': 1483 | songs = s.get_songs_from_artist(sel) 1484 | elif typ == 'album': 1485 | songs = s.get_songs_from_album(sel) 1486 | elif typ == 'song': 1487 | # single song -> wrap in list 1488 | songs = [Song(sel)] if 'Song' in globals() else [sel] 1489 | else: 1490 | print("Unsupported type for download") 1491 | return 1492 | 1493 | total = len(songs) 1494 | if total == 0: 1495 | print("No songs found to download") 1496 | return 1497 | print(f"Starting download of {total} songs...") 1498 | song_count.value = f"Songs to download: {total}" 1499 | song_count.update() 1500 | e.control.page.update() 1501 | sem = asyncio.Semaphore(10) 1502 | timeout = aiohttp.ClientTimeout(total=120) 1503 | completed = 0 1504 | async with aiohttp.ClientSession(timeout=timeout) as session: 1505 | # create tasks in batches of 10 1506 | tasks = [DownloadSong(song, output_folder=music_folder_path, skip=True).download_song_async(session, sem) for song in songs] 1507 | for fut in asyncio.as_completed(tasks): 1508 | try: 1509 | path = await fut 1510 | print(f"Downloaded: {path}, {completed}/{total} songs. ") 1511 | completed += 1 1512 | search_progress.value = completed / total 1513 | search_progress.update() 1514 | downloaded_count.value = f"Downloaded {completed}/{total} songs." 1515 | downloaded_count.update() 1516 | e.control.page.update() 1517 | except Exception as ex: 1518 | print(f"Song download failed: {ex}") 1519 | 1520 | if completed == total: 1521 | downloaded_count.value = f"all done! Downloaded {completed} songs." 1522 | else: 1523 | downloaded_count.value = f"Download completed with errors. Downloaded {completed}/{total} songs. JUST CLICK DOWNLOAD AGAIN TO GET THE MISSED ONES" 1524 | downloaded_count.update() 1525 | e.control.page.update() 1526 | 1527 | # run async download without blocking UI thread 1528 | try: 1529 | asyncio.run(run_download()) 1530 | print("Download runner completed") 1531 | 1532 | except Exception as err: 1533 | print(f"Download runner failed: {err}") 1534 | 1535 | search_btn = ft.ElevatedButton("Search", on_click=perform_search) 1536 | download_btn = ft.ElevatedButton("Download", on_click=start_download) 1537 | song_count = ft.Text("") 1538 | downloaded_count = ft.Text("") 1539 | 1540 | search_tab = ft.Container( 1541 | ft.SafeArea( 1542 | content=ft.Column([ 1543 | ft.Divider(opacity=0, height=20), 1544 | folder_picker, 1545 | ft.Divider(opacity=0, height=20), 1546 | ft.Text("Search Artist or Album:"), 1547 | ft.Row([search_query, search_btn]), 1548 | ft.Divider(opacity=0), 1549 | search_candidates_dropdown, 1550 | search_result_box, 1551 | ft.Divider(opacity=0), 1552 | download_btn, 1553 | song_count, 1554 | search_progress, 1555 | downloaded_count, 1556 | gesture_detector.detector, 1557 | 1558 | ]) 1559 | ), 1560 | visible=False 1561 | ) 1562 | 1563 | page.spotify_tab=spotify_tab 1564 | page.youtube_tab = youtube_tab 1565 | page.apple_music_tab = apple_music_tab 1566 | page.search_tab = search_tab 1567 | page.overlay.extend([ get_directory_dialog]) 1568 | 1569 | page.add( 1570 | youtube_tab,spotify_tab,apple_music_tab, search_tab 1571 | ) 1572 | for i in range(0, 101): 1573 | pb.value = i * 0.01 1574 | time.sleep(0.1) 1575 | page.update() 1576 | 1577 | 1578 | ft.app(target=main) --------------------------------------------------------------------------------