Ejemplo n.º 1
0
def main():
    options = parse_args()

    r = Reddit(options.subreddit)

    info('Fecthing threads from Reddit')
    top_titles = r.top(options.period, options.limit)
    entities = [Entity(title) for title in top_titles]
    info('Found {} threads'.format(len(entities)))
    
    for entity in entities:
        try:
            entity.search_term = search_term_from_title(entity.reddit_title)
        except:
            error('Failed to convert Reddit title "{}" to a search term'.format(title))

    refresh_token = read_refresh_token(options.refresh_token_file)

    try:
        s = Spotify(options.spotify_client_id, options.spotify_client_secret, refresh_token)
    except Exception as e:
        error('Failed to create Spotify agent')
        error(e)
        return 1

    info('Searching Spotify for tracks')
    for entity in entities:
        try:
            entity.spotify_track = s.search_track(entity.search_term)
        except Exception as e:
            error(e)
            error('Skipping...')

    # list to Set to list - done to dedupe
    tracks_found = list(Set([entity.spotify_track for entity in entities if entity.spotify_track is not None]))
    info('Found {} Spotify tracks'.format(len(tracks_found)))

    if not (float(len(tracks_found)) / len(entities)) > options.search_threshold:
        error('Search of Spotify tracks under threshold of {}'.format(options.search_threshold))
        return 1

    if options.dry_run == False:
        try:
            info('Removing existing tracks from playlist')
            s.clear_playlist(options.playlist_id)
            info('Adding {} new tracks to playlist'.format(len(tracks_found)))
            s.add_tracks_to_playlist(options.playlist_id, tracks_found)
        except Exception as e:
            error(e)
            return 1

    info('Run completed successfully')
    return 0