Minor Changes (#23)

* made code a little cleaner

* switched to requests from mechanize

* fixed sys.path error

* place list.txt with spotdl.py and not in Music/list.txt

* change a sub-heading to 'Instructions for Downloading Songs'

* remove mechanize

* change error message

* remove random comments

* no extra print

* remove random dots
This commit is contained in:
Ritiek Malhotra
2016-12-27 01:41:27 +05:30
committed by GitHub
parent ea26cf8cbd
commit 2624cdace9
3 changed files with 50 additions and 74 deletions

View File

@@ -24,10 +24,10 @@ cd Spotify-Downloader
sudo pip install -r requirements.txt sudo pip install -r requirements.txt
``` ```
You'll also need to install avconv: You'll also need to install avconv:
```
sudo apt-get install libav-tools `sudo apt-get install libav-tools`
```
Use ```sudo python spotdl.py``` to launch the script. Use `sudo python spotdl.py` to launch the script.
#### Windows: #### Windows:
@@ -38,16 +38,16 @@ Copy all the contents of bin folder (of avconv) to Scripts folder (in your pytho
Download the zip file of this repository and extract its contents in your python's installation folder as well. Download the zip file of this repository and extract its contents in your python's installation folder as well.
Shift+right-click on empty area and open cmd and type: Shift+right-click on empty area and open cmd and type:
```
"Scripts/pip.exe" install -r requirements.txt `"Scripts/pip.exe" install -r requirements.txt`
```
Now to run the script type: Now to run the script type:
```
python.exe spotdl.py `python.exe spotdl.py`
```
(you can create a batch file shortcut to run the script just by double-click anytime) (you can create a batch file shortcut to run the script just by double-click anytime)
## Step by step Instructions for Downloading songs: ## Instructions for Downloading Songs:
First launch the script using the above command as mentioned for your OS. First launch the script using the above command as mentioned for your OS.
@@ -55,21 +55,21 @@ First launch the script using the above command as mentioned for your OS.
For example: For example:
◘ We want to download Hello by Adele, simply run the script and type ```adele hello```. ◘ We want to download Hello by Adele, simply run the script and type `adele hello`.
◘ The script will automatically look for the best matching song and download it in the folder ```Music/``` placed in your current directory. ◘ The script will automatically look for the best matching song and download it in the folder `Music/` placed in your current directory.
◘ It will now convert the song to an mp3. ◘ It will now convert the song to an mp3.
◘ Now, if we want to check it out the lyrics of that song, just type ```lyrics``` in the script and it should print out the lyrics for any last downloaded song. ◘ Now, if we want to check it out the lyrics of that song, just type `lyrics` in the script and it should print out the lyrics for any last downloaded song.
◘ Okay, lets play the song now. Just type ```play``` in the script. ◘ Okay, lets play the song now. Just type `play` in the script.
#### Downloading by Spotify Link: #### Downloading by Spotify Link:
For example: For example:
◘ We want to download the same song (i.e: Hello by Adele) but using Spotify Link this time that looks like ```http://open.spotify.com/track/1MDoll6jK4rrk2BcFRP5i7```, you can copy it from your Spotify desktop or mobile app by right clicking or long tap on the song and copy HTTP link. ◘ We want to download the same song (i.e: Hello by Adele) but using Spotify Link this time that looks like `http://open.spotify.com/track/1MDoll6jK4rrk2BcFRP5i7`, you can copy it from your Spotify desktop or mobile app by right clicking or long tap on the song and copy HTTP link.
◘ Now simply paste this link after running the script, it should download Hello by Adele. ◘ Now simply paste this link after running the script, it should download Hello by Adele.
@@ -79,7 +79,7 @@ For example:
◘ Similarly, we can now check out its lyrics or play it. ◘ Similarly, we can now check out its lyrics or play it.
◘ Just type ```exit``` to exit out of the script. ◘ Just type `exit` to exit out of the script.
#### What if we want to download multiple songs at once? #### What if we want to download multiple songs at once?
@@ -95,10 +95,10 @@ No problem!
``` ```
cd cd
cd Spotify-Downloader/Music cd Spotify-Downloader
sudo nano list.txt sudo nano list.txt
``` ```
(if you are on windows, just edit ```list.txt``` - i.e ```C:\Python27\Music\list.txt```) (if you are on windows, just edit `list.txt` - i.e `C:\Python27\list.txt`)
add all the songs you want to download, in our case it is: add all the songs you want to download, in our case it is:
@@ -108,11 +108,11 @@ the nights avicci
21 guns green day 21 guns green day
``` ```
◘ Now just run the script and type ```list```, it will automatically start downloading the songs you provided in ```list.txt```. ◘ Now just run the script and type ```list```, it will automatically start downloading the songs you provided in `list.txt`.
◘ You can stop downloading songs by hitting ```ctrl+c```, the script will automatically resume from the song where you stopped it the next time you want to download the songs using ```list```. ◘ You can stop downloading songs by hitting `ctrl+c`, the script will automatically resume from the song where you stopped it the next time you want to download the songs using `list`.
◘ To download all songs in your playlist, just select all the songs ```ctrl+a``` in Spotify desktop app, copy them ```ctrl+c``` and paste ```ctrl+v``` in ```list.txt```. ◘ To download all songs in your playlist, just select all the songs `ctrl+a` in Spotify desktop app, copy them `ctrl+c` and paste `ctrl+v` in `list.txt`.
## Brief info on Commands: ## Brief info on Commands:
``` ```

View File

@@ -1,4 +1,3 @@
mechanize
BeautifulSoup4 BeautifulSoup4
youtube_dl youtube_dl
pafy pafy

View File

@@ -1,46 +1,31 @@
#!/bin/python #!/bin/python
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import mechanize
import pafy
import os
import sys
import spotipy import spotipy
import eyed3 import eyed3
import requests
import pafy
import shutil
import os
import sys
#import spotipy.util as util #import spotipy.util as util
#print(sys.path[0]) os.chdir(sys.path[0])
os.chdir(sys.path[0] + '/')
if not os.path.exists("Music"): if not os.path.exists("Music"):
os.makedirs("Music") os.makedirs("Music")
open('Music/list.txt', 'a').close() open('list.txt', 'a').close()
spotify = spotipy.Spotify() spotify = spotipy.Spotify()
print('')
def loadMechanize():
global br
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [("User-agent","Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13")]
def searchYT(number): def searchYT(number):
#print(URL) items = (requests.request(method='GET', url=URL)).text
items = br.open(URL)
#print(items)
items = items.read()
#print(items)
zoom1 = items.find('yt-uix-tile-link') zoom1 = items.find('yt-uix-tile-link')
zoom2 = items.find('yt-uix-tile-link', zoom1+1) zoom2 = items.find('yt-uix-tile-link', zoom1+1)
zoom3 = items.find('yt-uix-tile-link', zoom2+1) zoom3 = items.find('yt-uix-tile-link', zoom2+1)
part = items[zoom1-100: zoom2] part = items[zoom1-100: zoom2]
items_parse = BeautifulSoup(part, "html.parser") items_parse = BeautifulSoup(part, "html.parser")
#items_parse = soup(items, "html.parser")
first_result = items_parse.find(attrs={'class':'yt-uix-tile-link'})['href'] first_result = items_parse.find(attrs={'class':'yt-uix-tile-link'})['href']
full_link = "youtube.com" + first_result full_link = "youtube.com" + first_result
#print(full_link) #print(full_link)
global video global video
@@ -65,7 +50,7 @@ def checkExists(islist):
trimSong() trimSong()
return True return True
else: else:
prompt = raw_input('Song with same name has already been downloaded.. re-download? (y/n/play): ') prompt = raw_input('Song with same name has already been downloaded. Re-download? (y/n/play): ')
if prompt == "y": if prompt == "y":
os.remove("Music/" + title + ".mp3") os.remove("Music/" + title + ".mp3")
elif prompt =="play": elif prompt =="play":
@@ -85,29 +70,28 @@ def getLyrics():
link = 'https://duckduckgo.com/html/?q=' + raw_title.replace(' ', '+') + '+musixmatch' link = 'https://duckduckgo.com/html/?q=' + raw_title.replace(' ', '+') + '+musixmatch'
else: else:
link = 'https://duckduckgo.com/html/?q=' + (content['artists'][0]['name'] + ' - ' + content['name']).replace(' ', '+') + '+musixmatch' link = 'https://duckduckgo.com/html/?q=' + (content['artists'][0]['name'] + ' - ' + content['name']).replace(' ', '+') + '+musixmatch'
loadMechanize() page = requests.request(method='GET', url=link).text
page = br.open(link)
page = page.read()
soup = BeautifulSoup(page, 'html.parser') soup = BeautifulSoup(page, 'html.parser')
link = soup.find('a', {'class':'result__url'})['href'] link = soup.find('a', {'class':'result__url'})['href']
page = br.open(link).read() page = requests.request(method='GET', url=link).text
soup = BeautifulSoup(page, 'html.parser') soup = BeautifulSoup(page, 'html.parser')
for x in soup.find_all('p', {'class':'mxm-lyrics__content'}): for x in soup.find_all('p', {'class':'mxm-lyrics__content'}):
print(x.get_text()).encode('utf-8') print(x.get_text()).encode('utf-8')
br.close()
else: else:
print('No log to read from..') print('No log to read from..')
def fixSong(): def fixSong():
print 'Fixing meta-tags..' print 'Fixing meta-tags'
audiofile = eyed3.load("Music/" + title + '.mp3') audiofile = eyed3.load("Music/" + title + '.mp3')
audiofile.tag.artist = content['artists'][0]['name'] audiofile.tag.artist = content['artists'][0]['name']
audiofile.tag.album = content['album']['name'] audiofile.tag.album = content['album']['name']
audiofile.tag.title = content['name'] audiofile.tag.title = content['name']
br.retrieve(content['album']['images'][0]['url'], 'Music/last_albumart.jpg') albumart = (requests.get(content['album']['images'][0]['url'], stream=True)).raw
bla = open("Music/last_albumart.jpg","rb").read() with open('last_albumart.jpg', 'wb') as out_file:
audiofile.tag.images.set(3,bla,"image/jpeg") shutil.copyfileobj(albumart, out_file)
audiofile.tag.save() albumart = open("last_albumart.jpg", "rb").read()
audiofile.tag.images.set(3,albumart,"image/jpeg")
audiofile.tag.save()
def playSong(): def playSong():
if not title == '': if not title == '':
@@ -117,9 +101,8 @@ def playSong():
print('Playing ' + title + '.mp3') print('Playing ' + title + '.mp3')
os.system('start ' + 'Music/' + title + '.mp3') os.system('start ' + 'Music/' + title + '.mp3')
def convertSong(): def convertSong():
print('Converting ' + title + '.m4a to mp3..') print('Converting ' + title + '.m4a to mp3')
if not os.name == 'nt': if not os.name == 'nt':
os.system('avconv -loglevel 0 -i "' + 'Music/' + title + '.m4a" -ab 192k "' + 'Music/' + title + '.mp3"') os.system('avconv -loglevel 0 -i "' + 'Music/' + title + '.m4a" -ab 192k "' + 'Music/' + title + '.mp3"')
else: else:
@@ -137,9 +120,9 @@ def isSpotify():
return False return False
def trimSong(): def trimSong():
with open('Music/list.txt', 'r') as fin: with open('list.txt', 'r') as fin:
data = fin.read().splitlines(True) data = fin.read().splitlines(True)
with open('Music/list.txt', 'w') as fout: with open('list.txt', 'w') as fout:
fout.writelines(data[1:]) fout.writelines(data[1:])
def trackPredict(): def trackPredict():
@@ -180,12 +163,10 @@ while True:
playSong() playSong()
elif raw_song == 'lyrics': elif raw_song == 'lyrics':
loadMechanize()
getLyrics() getLyrics()
elif raw_song == 'list': elif raw_song == 'list':
loadMechanize() f = open('list.txt', 'r').read()
f = open('Music/list.txt', 'r').read()
lines = f.splitlines() lines = f.splitlines()
for raw_song in lines: for raw_song in lines:
if not len(raw_song) == 0: if not len(raw_song) == 0:
@@ -212,13 +193,11 @@ while True:
except: except:
lines.append(raw_song) lines.append(raw_song)
trimSong() trimSong()
with open('Music/list.txt', 'a') as myfile: with open('list.txt', 'a') as myfile:
myfile.write(raw_song) myfile.write(raw_song)
print('Could not complete a Song download, will try later..') print('Failed to download song. Will retry after other songs.')
else: else:
try: try:
loadMechanize()
trackPredict() trackPredict()
searchYT(None) searchYT(None)
if not checkExists(False): if not checkExists(False):
@@ -229,7 +208,5 @@ while True:
fixSong() fixSong()
except KeyboardInterrupt: except KeyboardInterrupt:
graceQuit() graceQuit()
br.close()
except KeyboardInterrupt: except KeyboardInterrupt:
graceQuit() graceQuit()