Added downloading from spotify.

TODO: Two playing options - old stream and new download
This commit is contained in:
BarsTiger
2022-12-12 23:04:17 +02:00
parent 9d2bc0aeb6
commit 9dae35a537
15 changed files with 351 additions and 78 deletions

View File

51
modules/spotify/config.py Normal file
View File

@@ -0,0 +1,51 @@
import json
import os
from dataclasses import dataclass
from dataclasses_json import dataclass_json
@dataclass_json
@dataclass(frozen=True)
class SpotConfig:
client_id: str
client_secret: str
class SpotifyConfig:
@staticmethod
def default():
return {
"client_id": "5f573c9620494bae87890c0f08a60293",
"client_secret": "212476d9b0f3472eaa762d90b19b0ba8"
}
@staticmethod
def fix() -> None:
try:
with open("data/config.spotify", "w") as file:
json.dump(SpotifyConfig.default(), file)
except FileNotFoundError:
if not os.path.exists('data'):
os.mkdir('data')
SpotifyConfig.fix()
@staticmethod
def get() -> SpotConfig:
try:
with open("data/config.spotify", "r") as file:
return SpotConfig.from_dict(json.load(file))
except:
SpotifyConfig.fix()
return SpotifyConfig.get()
@staticmethod
def update(key: str, value: str | None) -> dict:
with open("data/config.spotify", "r") as file:
settings = json.load(file)
settings[key] = value
with open("data/config.spotify", "w") as file:
json.dump(settings, file)
return settings

View File

@@ -0,0 +1,57 @@
import requests
from urllib.parse import urlencode
from urllib.request import urlopen
from urllib.error import HTTPError
import re
from base64 import b64encode
from modules.spotify.config import SpotifyConfig
def reencode(text: str):
return b64encode(text.encode()).decode()
class Spotify(object):
def __init__(self):
try:
headers = {
'Authorization': f'Basic '
f'{reencode(f"{SpotifyConfig.get().client_id}:{SpotifyConfig.get().client_secret}")}',
}
data = {
'grant_type': 'client_credentials'
}
r = requests.post('https://accounts.spotify.com/api/token', headers=headers, data=data)
self.token = r.json()['access_token']
except Exception as e:
print(e)
def get_youtube_url(self, url) -> str | None:
track_id = url.split('/')[-1].split('?')[0]
r = requests.get(f"https://api.spotify.com/v1/tracks/{track_id}",
headers={'Authorization': f'Bearer {self.token}'})
if r.status_code == 400 or r.status_code == 401:
return None
track = r.json()
song_name = track['name']
artists = []
for artist in track['artists']:
artists.append(artist['name'])
artist_name = ' '.join(artists)
try:
query_string = urlencode({'search_query': artist_name + ' ' + song_name})
htm_content = urlopen('http://www.youtube.com/results?' + query_string)
search_results = re.findall(r'/watch\?v=(.{11})', htm_content.read().decode())
return f'http://www.youtube.com/watch?v={search_results[0]}'
except HTTPError:
return None