示例#1
0
def get_spotify_api():
    with open("spotify_secrets.json", "r") as file:
        spotify_secrets = json.load(file)
    sp = spotipy.Spotify(auth_manager=SpotifyPKCE(
        client_id=spotify_secrets["client_id"],
        redirect_uri=spotify_secrets["redirect_uri"],
        scope=" ".join(spotify_secrets["scope"]),
        cache_handler=_spotify_keyring_handler,
    ))
    try:
        yield sp
    finally:
        sp.__del__()
示例#2
0
    def _generate_api(self):
        logger.debug('Generating Spotipy object')
        redirect_uri = 'http://127.0.0.1:' + str(self.preferences['auth_port'])
        if int(self.preferences['auth_port']) not in self.POSSIBLE_PORTS:
            logger.debug(
                _('Port set in the preferences is not one of the supported ports.'
                  ))
            logger.debug(
                _('Something went very wrong, please report this issue on github.'
                  ))

        auth = SpotifyPKCE(client_id=self.CLIENT_ID,
                           redirect_uri=redirect_uri,
                           scope=self.SCOPES,
                           cache_path=self.ACCESS_TOKEN_CACHE)
        self.api = spotipy.Spotify(auth_manager=auth)
        return
示例#3
0
import asyncio
import websockets

from spotipy import Spotify
from spotipy.oauth2 import SpotifyPKCE

from params import Params

import time
from threading import Thread, Event

auth_manager = SpotifyPKCE(client_id="a9ed7f99384943dc98518ed396cd639a",
                            redirect_uri="http://localhost:7999/callback",
                            scope="playlist-read-private",
                            open_browser=False)

sp = Spotify(auth_manager=auth_manager)

event = Event()


async def handler(ws, path):
    event.wait()
    await ws.send(params.get_queue())


def start_server():    
    asyncio.set_event_loop(asyncio.new_event_loop())
    server = websockets.serve(handler, "0.0.0.0", 7999)

    asyncio.get_event_loop().run_until_complete(server)
示例#4
0
import spotipy
from spotipy.oauth2 import SpotifyPKCE

auth_manager = SpotifyPKCE(client_id='cc77361c432c4bc28740a3a27828b5ae',
                           redirect_uri='http://localhost:8888/callback/',
                           scope='playlist-read-collaborative playlist-read-private user-library-read')
spotify = spotipy.Spotify(auth_manager=auth_manager)
示例#5
0
文件: client.py 项目: digyx/Musik
from spotipy import Spotify
from spotipy.oauth2 import SpotifyPKCE

import asyncio, websockets, time, ast
import platform, subprocess


auth_manager = SpotifyPKCE(client_id="a9ed7f99384943dc98518ed396cd639a",
                            redirect_uri="http://localhost:7998/callback",
                            scope="streaming user-read-playback-state user-modify-playback-state")

sp = Spotify(auth_manager=auth_manager)
device_id = sp.current_playback()['device']['id']

def play(uris: str):
    sp.start_playback(uris=uris, device_id=device_id)
    sp.repeat("context")
    sp.shuffle(False)


def pause():
    sp.pause_playback()


def print_track(track):
    if platform.system() == "Windows":
        subprocess.run("cls", shell=True)
    else:
        subprocess.run("clear", shell=True)

    print("Now playing:")
示例#6
0
def main():
    try:
        youtube_secret = json.load(open("youtube_client.json"))["client_secret"]
    except IOError:
        print('Failed to load youtube_client.json')
        return

    try:
        spotify_json = json.load(open("spotify_client.json"))
        spotify_secret = spotify_json["client_secret"]
        spotify_id = spotify_json["client_id"]
    except IOError:
        print('Failed to load spotify_client.json')
        return

    print('client secrets loaded, initialising youtube api')
    youtube = googleapiclient.discovery.build("youtube", "v3", developerKey=youtube_secret)

    print('Loading youtube playlists')
    request = youtube.playlists().list(part="snippet,contentDetails", maxResults=50, channelId=channel_id)

    response = request.execute()

    playlists = []
    while request is not None:
        response = request.execute()
        for item in response["items"]:
            playlists.append((item["snippet"]["title"], item["id"]))
        request = youtube.playlists().list_next(request, response)

    while True:
        print('Select playlist:')
        print(', '.join([title for title, _ in playlists]))
        selected = input()
        youtube_playlist_id = 0
        for title, pid in playlists:
            if title == selected:
                youtube_playlist_id = pid
                break

        print('Loading youtube playlist items')
        request = youtube.playlistItems().list(part="snippet,contentDetails", maxResults=50, playlistId=youtube_playlist_id)

        response = request.execute()

        playlist_entries = []
        while request is not None:
            response = request.execute()
            for item in response["items"]:
                playlist_entries.append((item["snippet"]["title"], item["contentDetails"]["videoId"]))
            request = youtube.playlistItems().list_next(request, response)

        print(f'Playlist Size: {len(playlist_entries)}')
        print('Loading spotify api with auth')
        #sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=spotify_id, client_secret=spotify_secret))
        sp = spotipy.Spotify(auth_manager=SpotifyPKCE(client_id=spotify_id, redirect_uri='https://www.alexdenford.com/', scope=spotify_scopes))

        print('Auth request sent')
        spotify_tracks = []

        result_fmt = '{}\t\t\t->\t\t\t{}'

        print('Requesting / searching spotify tracks')
        for title, video_id in playlist_entries:
            if 'Deleted video' in title:
                continue

            if '-' not in title:
                # find channel now from the video id
                video = youtube.videos().list(part="snippet", id=video_id, maxResults=1).execute()
                if len(video['items']) != 0:
                    channel_title = video['items'][0]['snippet']['channelTitle']
                    title = f'{channel_title} - {title}'

            pre_regex = title
            title = remove_block(remove_block(remove_block(remove_block(title, "【】"), "{}"), "()"), "[]")
            title = re.sub('- Topic', '', title, re.IGNORECASE)
            title = re.sub('Official Video', '', title, re.IGNORECASE)
            title = re.sub('Official Music Video', '', title, re.IGNORECASE)
            title = re.sub(' & ', ' ', title)
            
            ft_idx = title.lower().find(' ft.')
            if ft_idx == -1:
                ft_idx = title.lower().find(' ft ')

            if ft_idx != -1:
                end_idx = min(title.find('-', ft_idx), title.find('.', ft_idx))
                new_title = title[:ft_idx] + '' if end_idx == -1 else title[end_idx+1:]
                title = new_title

            if len(title) == 0:
                print(result_fmt.format(pre_regex, 'NO MATCH FOUND (NULL SEARCH TERM)'))
                continue

            results = sp.search(q=title, limit=1)
            for item in results['tracks']['items']:
                spotify_tracks.append(item['id'])
                print(result_fmt.format(title, '{} - {}'.format(', '.join([x['name'] for x in item['artists']]), item['name'])))

            if len(results['tracks']['items']) == 0:
                print(result_fmt.format(title, 'NO MATCH FOUND'))

        # create playlist
        print(f'Total matches found: {len(spotify_tracks)}')
        print('Creating spotify playlist')
        playlist = sp.user_playlist_create( user=spotify_user_id, name=f'Youtube - {selected}', public=False)

        print('Adding tracks to spotify playlist')
        for i in range(0,len(spotify_tracks),99):
            sp.user_playlist_add_tracks(user=spotify_user_id, playlist_id=playlist['id'], tracks=spotify_tracks[i:min(i + 99, len(spotify_tracks) - 1)])

        print('Complete\n')
示例#7
0
 def __init__pkce(self) -> SpotifyPKCE:
     scope = "user-read-currently-playing"
     redirect_uri = "http://localhost:8080/"
     
     return SpotifyPKCE(
         redirect_uri=redirect_uri, scope=scope, cache_path=self.__cache_path)
示例#8
0
    'user-top-read',
    'user-read-playback-position',
    'user-read-playback-state',
    'user-modify-playback-state',
    'user-read-currently-playing',
    'streaming',
    'playlist-read-private',
    'playlist-read-collaborative',
    'user-follow-read',
    'user-library-read',
    'user-read-email',
    'user-read-private',
]

spotify_cache_handler = SessionCacheHandler()
sp = spotipy.Spotify(auth_manager=SpotifyPKCE(
    scope=SCOPES, cache_handler=spotify_cache_handler))


@app.before_request
def make_session_permanent():
    session.permanent = True


@app.route('/')
def index():
    """Look for valid site access token"""
    if not site_access_token_is_valid():
        return redirect(url_for('coming_soon'))
    if not spotify_access_token_is_valid():
        return sign_in_with_spotify()
    access_token = spotify_cache_handler.get_cached_token()['access_token']