forked from MiniDude22/Pandora-Downloader
/
flask_server.py
67 lines (50 loc) · 2.11 KB
/
flask_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import os
import re
import urllib
from flask import Flask, request, jsonify
from mutagen.mp4 import MP4, MP4Cover
# Modify this line to change where the songs are saved
# Possible Variables - Mix and match as desired
# {station} {artist} {album} {title}
save_template = os.sep.join((
os.path.expanduser("~"),
'Music',
'Pandora',
"{station}",
"{artist}",
# "{album} - {title}.m4a"
"{title}.m4a"
)).encode('utf-8')
app = Flask( "Pandora Downloader Server" )
@app.route( '/download', methods=['POST'] )
def pandoraDownloader():
# Build the song's path - remove any invalid characters
song_path = save_template.format(
station = re.sub(u'[<>\*:\\/\"|?]', '', request.form['station'].encode('utf-8') ),
artist = re.sub(u'[<>\*:\\/\"|?]', '', request.form['artist' ].encode('utf-8') ),
album = re.sub(u'[<>\*:\\/\"|?]', '', request.form['album' ].encode('utf-8') ),
title = re.sub(u'[<>\*:\\/\"|?]', '', request.form['title' ].encode('utf-8') )
).decode('utf-8')
# check to see if the file has been downloaded before!
if os.path.exists( song_path ):
print( 'Song found already' )
return jsonify( status = 'alreadyDownloaded' )
else:
print( 'Downloading "' + request.form['title'].encode('utf-8') + '"' )
# Create the directories if they don't exist
if not os.path.isdir( os.path.split(song_path)[0] ): os.makedirs( os.path.split(song_path)[0] )
# Download the song
urllib.urlretrieve( request.form['url'], song_path )
song = MP4( song_path )
song['\xa9nam'] = [ request.form['title'].encode('utf-8') ]
song['\xa9ART'] = [ request.form['artist'].encode('utf-8') ]
song['\xa9alb'] = [ request.form['album'].encode('utf-8') ]
albumArtRequest = urllib.urlopen( request.form['albumArt'] )
albumArt = MP4Cover( albumArtRequest.read() )
albumArtRequest.close()
song['covr'] = [ albumArt ]
song.save()
print( 'Download Complete!' )
return jsonify( status = 'success' )
if __name__ == '__main__':
app.run(debug=True)