1
0
Fork 0
mirror of https://github.com/Findus23/RadioStats.git synced 2024-09-19 16:03:48 +02:00
RadioStats/spotify.py

58 lines
1.8 KiB
Python
Raw Normal View History

2018-02-23 20:56:54 +01:00
import re
2018-02-15 21:07:26 +01:00
import sys
2018-02-15 21:02:51 +01:00
from time import sleep
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from config import spotify
from models import *
crm = SpotifyClientCredentials(**spotify)
sp = spotipy.Spotify(client_credentials_manager=crm)
2018-02-15 21:07:26 +01:00
if len(sys.argv) > 1:
2018-02-15 21:09:03 +01:00
limit = int(sys.argv[1])
2018-02-15 21:07:26 +01:00
else:
limit = 50
2018-02-15 21:02:51 +01:00
2018-02-23 20:56:54 +01:00
query = Song.select().where((Song.show == 0))
2018-02-23 21:02:23 +01:00
if not len(sys.argv) > 3 or sys.argv[2] != "force":
2018-02-23 20:56:54 +01:00
query = query.where(Song.spotify_data.is_null())
else:
2018-02-23 21:02:23 +01:00
starting = int(sys.argv[2])
print("fetching empty starting from {id}".format(id=starting))
query = query.where((Song.spotify_data == 0) & (Song.id >= starting))
2018-02-23 20:56:54 +01:00
for song in query.limit(limit):
song.title = song.title.replace("+", " ")
2018-02-15 21:02:51 +01:00
print(song.title)
if song.artist.isupper():
song.artist = song.artist.title()
if song.title.isupper():
song.title = song.title.title()
2018-02-17 10:27:46 +01:00
print(song.id)
2018-02-15 21:02:51 +01:00
sleep(0.1)
2018-02-23 20:56:54 +01:00
searchtitle = re.sub("[\(\[].*?[\)\]]", "", song.title)
searchartist = song.artist.replace("&", "").replace("Feat.", "")
results = sp.search(q='title:' + searchtitle + ' artist:' + searchartist, type='track', limit=1)
2018-02-15 21:02:51 +01:00
if len(results["tracks"]["items"]) == 0:
song.spotify_data = False
2018-02-23 21:00:27 +01:00
print("not found")
2018-02-15 21:02:51 +01:00
else:
2018-02-23 21:00:27 +01:00
print("found")
2018-02-15 21:02:51 +01:00
track = results["tracks"]["items"][0]
song.spotify_url = track["external_urls"]["spotify"]
song.preview_url = track["preview_url"]
images = track["album"]["images"]
2018-02-15 21:45:43 +01:00
if len(images):
song.image_large = images[0]["url"]
song.image_small = images[-1]["url"]
2018-02-15 21:02:51 +01:00
song.spotify_data = True
# print(song.title)
# print(track["name"])
# print(song.artist)
# print(", ".join([a["name"] for a in track["artists"]]))
song.save()