-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplaylist_updater.py
204 lines (156 loc) · 6.28 KB
/
playlist_updater.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import logging
from . import scraping
from .spotify import SpotifyApi
from .db import Session, Song
from .exceptions import NoHistoryFound
class Updater(object):
def __init__(self):
self.spotify = SpotifyApi()
self.is_authenticated = False
# Add new scrapers here
self.scrapers = [
scraping.KSHEScraper(),
# scraping.EagleScraper(), # TODO: Eagle website not reachable in the EU
# scraping.Q1043Scrapper(),
# scraping.WMGKScrapper(),
# scraping.KLOScrapper()
]
def spotify_auth(self):
"""Authenticates using Authorization Code Flow.
Returns:
str: URL to redirect to
"""
url = self.spotify._authorization_code_flow_authentication()
return url
def spotify_callback(self, authorization_code):
"""Function called by Spotify with access token in the request
parameters.
Args:
authorization_code (str): Authorization code
"""
response = self.spotify._client_credentials_authentication(
authorization_code
)
logging.info(response)
self.spotify._access_token = response['access_token']
self.spotify._token_type = response['token_type']
self.spotify._token_expires_in = response['expires_in']
if response.get('access_token'):
# TODO: add authenticated until timestamp
self.is_authenticated = True
def sync_db_with_existing_songs(self, playlist_id):
"""If the playlist already exist, look for songs in it and stores them
in the local database so we don't add duplicates.
Args:
playlist_id (str): Playlist ID
"""
playlist_exists = self.spotify.check_playlist_exists(playlist_id)
if playlist_exists:
tracks = self.spotify.get_track_uris_from_playlist(playlist_id)
session = Session()
for uri in tracks:
song = Song(playlist_id=playlist_id, spotify_uri=uri)
session.add(song)
try:
session.commit()
except:
continue
session.close()
session = Session()
count = session.query(Song).count()
logging.info("Playlist has {0} songs after sync".format(count))
session.close()
def search_songs_in_spotify(self, radio_history):
"""Retrieve songs informations from title and artist using Spotify
Search API.
Args:
radio_history (list(dict)): list of dict with title and \
artist as keys
Returns:
list(dict): list of dict of spotify songs
"""
spotify_songs = [self.spotify.search_track(s['title'], s['artist'])
for s in radio_history if 'title' in s]
spotify_songs = [s for s in spotify_songs if 'spotify_uri' in s]
return spotify_songs
def filter_and_save_songs_to_db(self, spotify_songs,
scraper_name, playlist_id):
"""Filter out songs that have already been added and add the
remaining songs to the playlist.
Args:
spotify_songs (list(dict)): List of spotify songs as dict
scraper_name (str): Scraper class name
Returns:
list(dict): List of spotify songs that are not in the playlist yet
"""
# save tracks in DB
session = Session()
spotify_filtered_songs = []
for i, song in enumerate(spotify_songs):
# Don't save and upload song if it exists
match = session.query(Song)\
.filter_by(
spotify_uri=song['spotify_uri'],
playlist_id=playlist_id
)\
.first()
if match is None:
song["scraper_name"] = scraper_name
song["playlist_id"] = playlist_id
session.add(Song(**song))
spotify_filtered_songs.append(song)
else:
logging.warning('{0} already in playlist'
.format(song['song_name']))
session.commit()
return spotify_filtered_songs
def add_songs_to_playlist(self, spotify_songs, playlist_id):
"""Add spotify songs to a playlist, using songs URI.
Args:
spotify_songs (list(dict)): List of spotify songs
Returns:
json: Json response from the Spotify API
"""
logging.info('will add {0} tracks'.format(len(spotify_songs)))
response = self.spotify.add_tracks_to_playlist(
[s['spotify_uri'] for s in spotify_songs],
playlist_id
)
return response
def single_scraper_pipeline(self, scraper):
# get song history
try:
song_history = scraper.get_song_history()
except NoHistoryFound:
return {}
# spotify songs
spotify_songs = self.search_songs_in_spotify(song_history)
# filter out already present songs and sync database
spotify_filtered_songs = self.filter_and_save_songs_to_db(
spotify_songs,
scraper_name=scraper.name,
playlist_id=scraper.playlist_id
)
# upload the filtered out songs to the spotify playlist
_ = self.add_songs_to_playlist(
spotify_filtered_songs,
playlist_id=scraper.playlist_id
)
return {
"scraper": scraper.name,
"playlist_id": scraper.playlist_id,
"songs": spotify_filtered_songs
}
def scrap_and_update(self):
"""Run the whole pipeline for every scraper:
- Scrap the concerned website and get their song history
- Search for the songs in Spotify
- Filter the songs already in playlist and save them to DB
- Add the filtered songs to the playlist
Returns:
list(dict): Inserted songs
"""
inserted_songs = [self.single_scraper_pipeline(scraper)
for scraper in self.scrapers]
n_inserted_songs = sum([len(r["songs"]) for r in inserted_songs])
return inserted_songs, n_inserted_songs