Ejemplo n.º 1
0
def save_preferences(preferences):
    """
    Save user preferences for search results 
    Accepts required dic param of song:uri, artist:proper artist name key formats 
    Returns None 
    ...
    """

    content = None

    if os.path.exists(
            os.path.join(melon_dir, 'preferences.json')
    ):  # content is not None if both file exists AND file has content
        content = others_help.file_contents(melon_dir, 'preferences.json')

    if content is None:
        content = preferences
    else:  # add to content from file
        for category in preferences:  # desired, blacklist
            for item in preferences[category]:
                content[category][item] = preferences[category][item]

    if others_help.file_contents(melon_dir, 'preferences.json',
                                 data=content) is None:
        raise Exception('Error saving preferences.')
Ejemplo n.º 2
0
def create_tops(period):
    """
    Parses 'Melon''s top songs charts for the top songs in South Korea, creates files 
    Accepts string param, only of 'hits', 'day', 'week', 'month' 
    Returns None
    """

    periods = get_categories()

    others_help.print_alert(
        f'create_tops(): Beginning top songs charts creation for {period} period(s)...'
    )

    if not periods.get(period, None):
        others_help.print_error(
            "Error. Invalid period, must be ('hits', 'day', 'week', 'month')")
        return

    url = periods.get(period, None)
    headers = {
        'User-Agent': 'test',
        'Content-type': 'text/html',
    }

    response = requests.get(
        url, headers=headers
    )  # APART FROM REQUESTS_GENERAL BECAUSE USES response.text -- this is used only once

    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'lxml')
        all_info = soup

        response = {}

        try:
            table = all_info.find('table')

            for row in table.find_all('tr'):
                try:
                    title = row.find('div', class_='rank01')
                    title = title.span.a.text
                    author = row.find('div', class_='rank02')
                    author = author.a.text
                    response[title] = author
                except:
                    pass

            if others_help.file_contents(
                    melon_dir, f'{period}.json', data=response) is None:
                raise Exception(f'Error writing contents to {period}.json.')

            others_help.print_alert(
                f'create_tops(): Added data for {period} period(s)...')

        except:
            others_help.print_error('Error during initial parsing.')
            return
    else:
        others_help.print_error(f"Response Error: {response.status_code}")
        return
Ejemplo n.º 3
0
def get_tops(select=None):
    """
    Gets top items for all or select Melon chart category top songs 
    Accepts an optional array of select charts, default is every chart 
    Returns None
    """

    if select:
        if not isinstance(select, list):
            raise Exception(
                'get_tops(): optional param must be an array/list.')
    else:
        select = get_categories()

    categories = get_categories()
    response = {}

    for chart in select:
        if not categories.get(chart, None):
            raise Exception(
                f'get_tops(): List item "{chart}" is invalid, must be "hits", "day", "week", or "month".'
            )

        charts = others_help.file_contents(melon_dir, f'{chart}.json')

        response[chart] = charts

    return response
Ejemplo n.º 4
0
def save_playlist_info(playlist_info):
    """
    Saves important information about playlist post-creation 
    Accepts dict of category:playlist-info key:value pairs 
    Returns None 
    """
    if others_help.file_contents(
            spotify_dir, 'playlist-info.json', data=playlist_info) is None:
        raise Exception('Failed to save playlist post-processing information.')
Ejemplo n.º 5
0
def save_results(search_results, postfix):
    """
    Saves user search results 
    Accepts dict of search results and string postfix param for file 
    Returns None 
    """

    for category in search_results:
        if others_help.file_contents(melon_dir,
                                     f'{category}-{postfix}.json',
                                     data=search_results[category]) is None:
            raise Exception(f'Error saving search results for {category}.')
Ejemplo n.º 6
0
def get_playlist_ids():
    """
    Gets playlist ids 
    No params 
    Returns dictionary of playlist ids 
    """

    playlist_info = others_help.file_contents(spotify_dir,
                                              'playlist-info.json')
    if playlist_info is None:
        raise Exception('Error trying to load playlist-info.json.')

    for category in playlist_info:
        uri = playlist_info[category]
        playlist_id = uri.split(':')[-1]
        playlist_info[category] = playlist_id

    return playlist_info
Ejemplo n.º 7
0
def get_processed_results(select):
    """
    Get parsed results 
    No params 
    Returns dict of chart:CERTAIN uris  
    """

    uris = {}

    for category in select:
        category_uris = others_help.file_contents(
            melon_dir, f'{category}-post-results.json')
        if category_uris is None:
            raise Exception(
                f'Error loading results for {category}-post-results.json.')

        uris[category] = category_uris

    return uris
Ejemplo n.º 8
0
def process_results(select):
    """
    User parses search results 
    Accepts array of user's selected charts 
    Returns None 
    """

    for category in select:

        results = others_help.file_contents(melon_dir,
                                            f'{category}-pre-results.json')
        if not results:
            raise Exception(
                f'Error trying to load {category}-pre-results.json.')

        msg = f"""
            For "{category}" category there are... \n
            {len(results['CERTAIN'])} Certains \n
            {len(results['EXCEPTIONS'])} Exceptions \n
            {len(results['UNCERTAIN'])} Uncertains \n
            What do you want to do... "process" or "pass" (just keep certains)? 
        """
        choice = others_help.validate_choices(['process', 'pass'], msg=msg)

        if choice == 'pass':

            processed = {
                category: results['CERTAIN'],
            }

            save_results(processed, 'post-results')

        else:

            if process_help(category, results) is None:
                raise Exception(
                    f'Failed to process results for "{category}" category.')