Ejemplo n.º 1
0
def get_client(token_file, credentials_file):
    token = read_json(token_file)['token']
    cl = Client.from_token(token)
    if cl.me.account.login is None:
        token = generate_token(credentials_file)  # TODO: ask user for input
        save_json(token_file, wrap_token(token))
        cl = Client.from_token(token)
    return cl
Ejemplo n.º 2
0
def init_client(login=None,
                password=None,
                token=None,
                captcha_answer=None,
                captcha_key=None):
    client = captcha = None
    if token:
        try:
            client = Client.from_token(token)
        except BaseException as ex:
            client = None

    if login and password:

        try:
            client = Client.from_credentials(login, password, captcha_answer,
                                             captcha_key)
        except Captcha as e:
            captcha_key = e.captcha.x_captcha_key
            e.captcha.download(
                'ymapp/static/captchas/{}_captcha.png'.format(captcha_key))
            captcha = {
                'file': '/static/captchas/{}_captcha.png'.format(captcha_key),
                'cp_key': captcha_key
            }
        except BaseException as ex:
            flash(str(ex))

    return client, captcha
Ejemplo n.º 3
0
def import_pl():
    spotify_manager = SpotifyManager()
    spotify_manager.auth()

    client = Client.from_token(session.get('yandex_token'))
    ids = request.form.getlist('for_import[]')
    if ids:
        import_data = []
        for id in ids:
            try:
                playlist = client.users_playlists(kind=id)
            except BadRequest:
                flash("Не удалось выполнить запрос в Яндекс.Музыке")
            else:
                track_ids = [track['id'] for track in playlist[0].tracks]
                if track_ids:
                    tracks = client.tracks(track_ids)
                    import_data.append({
                        "name": playlist[0].title,
                        "description": "Yandex.Music",
                        "tracks": tracks
                    })

        result = spotify_manager.import_playlists(import_data)
    else:
        flash("Не заданы ID плейлистов для импорта!")

    times = css_js_update_time()

    return render_template('index.html',
                           result=result,
                           progress=100,
                           spotify_data=spotify_manager.user_data,
                           times=times)
Ejemplo n.º 4
0
 def __init__(self, token):
     self.client = Client.from_token(token)
     self.liked_tracks_dict = OrderedDict()
     self.liked_tracks_list = list()
     self.tracks = self.client.users_likes_tracks()
     self.load_liked_tracks_json()
     self.settings_dict = {}
Ejemplo n.º 5
0
 def try_cached_auth(self, config):
     token = self.get_token()
     if token:
         logging.info("Trying to login with previously saved token.")
         try:
             self.client_obj = YamClient.from_token(token)
         except Exception as exc:
             logging.info("Could not login with token")
             logging.exception(exc)
             pass
Ejemplo n.º 6
0
 def try_auth(self, config):
     self.try_cached_auth(config)
     if self.client_obj:
         self.authenticated = True
         self.client_obj.logger.setLevel(logging.ERROR)
         return
     logging.info("Trying to authenticate with \"{}\" method.".format(
         config.auth_method))
     if config.auth_method == YAMU_AUTH_METHOD_USERNAME:
         self.client_obj = YamClient.from_credentials(
             config.username,
             config.password,
             captcha_callback=self.handle_captcha)
     elif config.auth_method == YAMU_AUTH_METHOD_TOKEN:
         self.client_obj = YamClient.from_token(config.token)
     else:
         self.authenticated = False  # It's the default, but setting explicitly just in case
         raise RuntimeError("Invalid authentication method: {}".format(
             config.auth_method))
     self.authenticated = True
     self.write_token()
Ejemplo n.º 7
0
    def __init__(self, username=None, password=None):
        self.__client = None

        token = None
        try:
            with open(YandexMusic.__cache_path, 'r', encoding='utf-8') as f:
                logger.debug(f'reading token: {YandexMusic.__cache_path}')
                token = f.read()
        except FileNotFoundError:
            pass

        if token is not None:
            self.__client = Client.from_token(token)
        else:
            logger.info(f'token not found, logging in: {username}')

            self.__client = Client.from_credentials(username, password)

            with open(YandexMusic.__cache_path, 'w', encoding='utf-8') as f:
                logger.debug(f'write token: {YandexMusic.__cache_path}')
                f.write(self.__client.token)

        login = self.__client.me.account.login
        logger.info(f'logged in: {login}')

        pl = self.__client.users_likes_tracks()
        favorites = YandexPlaylist('user likes', pl.tracks)

        logger.debug('loaded user favorites')

        playlists = []
        for lst in self.__client.users_playlists_list():
            pl = self.__client.users_playlists(lst.kind)[0]
            playlists += [YandexPlaylist(pl.title, pl.tracks, pl.visibility)]

        logger.debug('loaded user playlists')

        super().__init__(favorites, playlists)
Ejemplo n.º 8
0
from os import remove, path
from datetime import timedelta
from django.utils import timezone
from hashlib import sha1
from yandex_music.client import Client
from math import ceil

from django.core.files.storage import default_storage
from django.core.files import File
from django.shortcuts import render
from django.conf import settings
from django.core.exceptions import PermissionDenied
from .models import Track

client = Client.from_token(settings.YANDEX_MUSIC_TOKEN)


def index(request):
    if not request.session.get('user_id', False):
        request.session['user_id'] = sha1(
            str.encode(str(timezone.now().timestamp()))).hexdigest()
    context = {
        'track_list': Track.objects.all().order_by(*['-rate', 'add_at'])
    }
    return render(request, 'playlist/index.html', context)


def add(request):
    if request.method == "POST":
        id_value = str(request.POST['id'])
        track = client.tracks(id_value)[0]