void search_complete(sp_search *result, void *userdata)
{
  int i;
  folder_t *folder = (folder_t *)userdata;
  file_t *file;

  printf("Spotify: Search complete, tracks: %d\n", sp_search_num_tracks(result));

  for(i = 0; i < sp_search_num_tracks(result); i ++) {
    file = calloc(1, sizeof(file_t));
    file->track = sp_search_track(result, i);
    strncpy(file->name, sp_artist_name(sp_track_artist(file->track, 0)), MAX_NAME_LENGTH);
    strcat(file->name, " - ");
    strcat(file->name, sp_track_name(file->track));
    strcat(file->name, ".wav");

    printf("Spotify: Adding track to folder: %s\n", file->name);

    if(i == 0)
      folder->files = file;
    else {
      file->next = folder->files;
      folder->files = file;
    }
  }
}
Exemple #2
0
bool search_is_album(size_t i)
{
	if(sp_search_num_tracks(search)<= i && i < (sp_search_num_tracks(search)+sp_search_num_albums(search)))
	{
		return 1;
	}
	return 0;
}
void
SpotifySearch::addSearchedTrack( sp_search *result, void *userdata)
{
    qDebug() << Q_FUNC_INFO;
    sp_playlist *playlist = reinterpret_cast<sp_playlist*>(userdata);
    if(!sp_playlist_is_loaded( playlist ) )
    {
        qDebug() << "Search Playlist is not loaded";
        return;
    }

    // Need to pass a ** to add_tracks
    sp_track **tracks = static_cast<sp_track **>(malloc(sizeof(sp_track*)));

    if( sp_search_num_tracks( result ) > 0 )
    {
        int num = qMin( sp_search_num_tracks( result ), 1 );
        for( int i = 0; i < num; i++ )
        {
            sp_track *const tr = sp_search_track( result, i );
            if( !tr || !sp_track_is_loaded( tr ) ) {
                qDebug() << "Got still loading track, skipping";
                continue;
            }

            qDebug() << "Adding track to playlist" << sp_track_name( tr );
            *(tracks++) = tr;
            sp_error err = sp_playlist_add_tracks(playlist, tracks, 1, sp_playlist_num_tracks( playlist ), SpotifySession::getInstance()->Session());

            switch(err) {
                case SP_ERROR_OK:
                    qDebug() << "Added tracks to pos" << sp_playlist_num_tracks( playlist )-1;
                    break;
                case SP_ERROR_INVALID_INDATA:
                    qDebug() << "Invalid position";
                    break;

                case SP_ERROR_PERMISSION_DENIED:
                    qDebug() << "Access denied";
                    break;
                default:
                    qDebug() << "Other error (should not happen)";
                    break;
                }
        }

    }
    delete []tracks;

}
Exemple #4
0
/**
 * Prints the Title - Artists for each item in the search result
 */
static void print_search(sp_search *search) {
    int i;
    for (i=0; i<sp_search_num_tracks(search); i++) {
        sp_track *track = sp_search_track(search, i);
        if (track == NULL) {
            fprintf(stderr, "Search track was null.\n");
            return;
        }
        else {
            int artistBufferSize = 16;
            char* artistBuffer = malloc (artistBufferSize * sizeof(char));
            memset(artistBuffer, '\0', artistBufferSize * sizeof(char));
            int nArtists = sp_track_num_artists(track);
            int j;
            for (j=0; j<nArtists; j++) {
                sp_artist *artist = sp_track_artist(track, j);
                strcat_resize(&artistBuffer, &artistBufferSize, sp_artist_name(artist));
                if (j < nArtists - 1)
                    strcat_resize(&artistBuffer, &artistBufferSize, ",");
//                sp_artist_release(artist);
            }
            printf("\"%s\" - %s\n", sp_track_name(track), artistBuffer);
            
            free (artistBuffer);
        }
//        sp_track_release(track);
    }
}
void QSpotifySearch::populateTracks(sp_search *search)
{
    m_trackResults->clear();
    if (m_enablePreview)
        m_trackResultsPreview->clear();

    auto sourceList = QSpotifySession::instance()->playQueue()->m_sourceTrackList;
    if(sourceList == m_trackResults || sourceList == m_trackResultsPreview) {
        QSpotifySession::instance()->playQueue()->m_sourceTrackList = nullptr;
    }

    if (search) {
        int c = sp_search_num_tracks(search);
        for (int i = 0; i < c; ++i) {
            if (auto strack = sp_search_track(search, i)) {
                auto track = QSpotifyCacheManager::instance().getTrack(strack);
                if(m_enablePreview && i < m_numPreviewItems)
                    m_trackResultsPreview->appendRow(track);
                m_trackResults->appendRow(track);
                connect(QSpotifySession::instance()->user()->starredList(), SIGNAL(tracksAdded(QVector<sp_track*>)), track.get(), SLOT(onStarredListTracksAdded(QVector<sp_track*>)));
                connect(QSpotifySession::instance()->user()->starredList(), SIGNAL(tracksRemoved(QVector<sp_track*>)), track.get(), SLOT(onStarredListTracksRemoved(QVector<sp_track*>)));
            }
        }
    }
}
Exemple #6
0
char *search_str_list()
{
	size_t tracks = sp_search_num_tracks(search);
	size_t albums = sp_search_num_albums(search);
	size_t playlists = sp_search_num_playlists(search);
	size_t size = API_MESSAGE_LEN*(albums+tracks);
	char *ret = malloc(size);
	ret[0] = '\0';
	int i;
	for(i=0; i<tracks; ++i)
	{
		num_pre(ret + strlen(ret), size, i, track_to_str,
				sp_search_track(search, i));
		strncat(ret + strlen(ret), "\n", size);
	}
	for(; i<(tracks+albums); ++i)
	{
		num_pre(ret + strlen(ret), size, i, album_to_str,
				sp_search_album(search, i-tracks));
		strncat(ret + strlen(ret), "\n", size);
	}
	for(; i<(tracks+albums+playlists); ++i)
	{
		num_pre(ret + strlen(ret), size, i, playlist_to_str,
				sp_search_playlist(search, i-tracks-albums));
		strncat(ret + strlen(ret), "\n", size);
	}

	return ret;
}
Exemple #7
0
bool search_is_track(size_t i)
{
	if(i<sp_search_num_tracks(search))
	{
		return 1;
	}
	return 0;
}
Exemple #8
0
static void sess_cb_search_complete_cb(sp_search *res, void *data)
{
  (void)data;

  log_append("Search result: %d/%d", sp_search_num_tracks(res), sp_search_total_tracks(res));
  ui_dirty(UI_SIDEBAR);
  ui_dirty(UI_TRACKLIST);
  ui_update_post(0);
}
Exemple #9
0
void search_for_tracks_at(sp_session *session, char *buf, size_t len, size_t i, bool (*f)(sp_track *))
{
	if(search == NULL)
	{
		return;
	}
	buf[0] = '\0';
	if(search_is_track(i) && sp_track_is_loaded(sp_search_track(search, i)))
	{
		f(sp_search_track(search, i));
		if(buf != NULL)
		{
			track_to_str(buf, len, sp_search_track(search, i));
		}
	}
	if(search_is_album(i) && sp_album_is_loaded(sp_search_album(search, i-sp_search_num_tracks(search))))
	{
		sp_albumbrowse_create(session, sp_search_album(search, i-sp_search_num_tracks(search))
				,on_albumbrowse_complete, f);
		if(buf != NULL)
		{
			album_to_str(buf, len, sp_search_album(search, i-sp_search_num_tracks(search)));
		}
	}
	if(search_is_playlist(i))
	{
		sp_playlist *pl = sp_search_playlist(search, 
					i-sp_search_num_tracks(search)-sp_search_num_albums(search));
		if(sp_playlist_is_loaded(pl))
		{
			int j;
			for(j = 0; j < sp_playlist_num_tracks(pl); ++j)
			{
				f(sp_playlist_track(pl, j));
			}
			if(buf != NULL)
			{
				playlist_to_str(buf, len, pl);
			}
		}
	}
}
Exemple #10
0
static PyObject *Results_tracks(Results *self) {
    int count = sp_search_num_tracks(self->_search);
    PyObject *l = PyList_New(count);
    int i;
    for(i=0;i<count;++i) {
        Track *a = (Track *)PyObject_CallObject((PyObject *)&TrackType, NULL);
        a->_track = sp_search_track(self->_search, i);
        PyList_SetItem(l, i, (PyObject *)a);
    }
    Py_INCREF(l);
    return l;
}
Exemple #11
0
/**
 * @param  search   The search result
 */
static void get_search(sp_search *search)
{
        int i;
        json_t *json = json_object();

        json_t *tracks = json_array();
        json_object_set_new(json, "tracks", tracks);
        for (i = 0; i < sp_search_num_tracks(search); ++i){
            json_array_append_new(tracks, get_track(sp_search_track(search, i)));
        }
        json_object_set_new_nocheck(json, "query", json_string_nocheck(sp_search_query(search)));
        cmd_sendresponse(json, 200);
}
void SpotifyClient::SendSearchResponse(sp_search* result) {
  // Take the request out of the queue
  spotify_pb::SearchRequest req = pending_searches_.take(result);

  // Prepare the response
  spotify_pb::SpotifyMessage message;
  spotify_pb::SearchResponse* response = message.mutable_search_response();

  *response->mutable_request() = req;

  // Check for errors
  sp_error error = sp_search_error(result);
  if (error != SP_ERROR_OK) {
    response->set_error(sp_error_message(error));

    handler_->SendMessage(message);
    sp_search_release(result);
    return;
  }

  // Get the list of tracks from the search
  int count = sp_search_num_tracks(result);
  for (int i=0 ; i<count ; ++i) {
    sp_track* track = sp_search_track(result, i);
    ConvertTrack(track, response->add_result());
  }

  // Get the albums from the search.  All these should be resolved by now.
  QList<sp_albumbrowse*> browses = pending_search_album_browses_.take(result);
  foreach (sp_albumbrowse* browse, browses) {
    sp_album* album = sp_albumbrowse_album(browse);
    spotify_pb::Album* msg = response->add_album();

    ConvertAlbum(album, msg->mutable_metadata());
    ConvertAlbumBrowse(browse, msg->mutable_metadata());

    // Add all tracks
    const int tracks = sp_albumbrowse_num_tracks(browse);
    for (int i=0 ; i<tracks ; ++i) {
      ConvertTrack(sp_albumbrowse_track(browse, i), msg->add_track());
    }

    sp_albumbrowse_release(browse);
  }
Exemple #13
0
/**
 * Return JSON for query results of search
 * Remember to free memory of return value when done with it.
 *
 * Returns NULL on error.
 */
char* search_to_json(sp_search *search) {
    int i;
    int nTracks = sp_search_num_tracks(search);

    // pointer passed to strcat_resize, so this can't be a char array
    int json_size = 1024;
    char* json = malloc(json_size * sizeof(char));
    memset(json, '\0', json_size * sizeof(char));

    if (json == NULL)
    {
        fprintf(stderr, "Failed to allocate memory for JSON string.\n");
        return NULL;
    }
    strcat(json, "{\"track_results\":");

    strcat(json, "[");
    for (i=0; i < nTracks; i++)
    {
        sp_track *track = sp_search_track(search,i);
        if (!track_to_json(track, &json, &json_size, 0))
        {
          fprintf(stderr, "Failed to set track info in JSON buffer.\n");
          if (json)
            free(json);
          return NULL;
        }
        if (i < nTracks - 1)
          strcat_resize(&json, &json_size, ",");
        // Release the track
//        sp_track_release(track);
		// TODO: delete this
		  //sp_link* l;
		  //char url[256];
		  //l = sp_link_create_from_track(track,0);
		  //sp_link_as_string(l,url,sizeof(url));
		  //printf("\t\t%s\n", url);
	 }
    strcat_resize(&json, &json_size, "]}");
    return json;
}
Exemple #14
0
static void SP_CALLCONV search_complete(sp_search *search, void *userdata)
{
    debug("callback: search is complete");
	//g_menuChoice = -1;
	sp_error error = sp_search_error(search);
	if (error != SP_ERROR_OK) {
		fprintf(stderr, "Error: %s\n", sp_error_message(error));
		return;
	}

	int num_tracks = sp_search_num_tracks(search);
	if (num_tracks == 0) {
		printf("\nSorry, couldn't find that track.\n");
		return;
	}

	printf("Found track!\n");
	sp_track *track = sp_search_track(search, 0);
    queue_add_first(track);
    printf("Track added next in queue\n");
}
Exemple #15
0
static void on_search_complete(sp_search *search, void *userdata)
{
	debug("callback: on_search_complete");
	sp_error error = sp_search_error(search);
	if (error != SP_ERROR_OK) {
		fprintf(stderr, "Error: %s\n", sp_error_message(error));
		exit(1);
	}

	int num_tracks = sp_search_num_tracks(search);
	if (num_tracks == 0) {
		fprintf(stderr, "Sorry, couldn't find that track. =/\n\n");
		sp_search_release(search);
		g_playing = 0;
		return;
	}

	sp_track *track = sp_search_track(search, 0);
	play((sp_session*)userdata, track);
	sp_search_release(search);
}
Exemple #16
0
static void search_complete(sp_search *result, void *userdata)
{
	sp_track *track;
	sp_artist *artist;
	int i;
	(void)userdata;

	if (sp_search_error(result) == SP_ERROR_OK) {
		for (i = 0; i < sp_search_num_tracks(result); ++i) {
			track = sp_search_track(result, i);
			artist = sp_track_artist(track, 0);
			printf("%d. %s - %s\n",
			       i, sp_track_name(track), sp_artist_name(artist));
		}
		fflush(stdout);

	} else {
		fprintf(stderr, "failed to search: %s",
				sp_error_message(sp_search_error(result)));
	}

	sp_search_release(result);
}
Exemple #17
0
/**
 * Print the given search result with as much information as possible
 *
 * @param  search   The search result
 */
static void print_search(sp_search *search)
{
  int i;

  printf("Query          : %s\n", sp_search_query(search));
  printf("Did you mean   : %s\n", sp_search_did_you_mean(search));
  printf("Tracks in total: %d\n", sp_search_total_tracks(search));
  puts("");

  for (i = 0; i < sp_search_num_tracks(search); ++i)
    print_track(sp_search_track(search, i));

  puts("");

  for (i = 0; i < sp_search_num_albums(search); ++i)
    print_album(sp_search_album(search, i));

  puts("");

  for (i = 0; i < sp_search_num_artists(search); ++i)
    print_artist(sp_search_artist(search, i));

  puts("");
}
Exemple #18
0
static void SP_CALLCONV search_complete(sp_search *search, void *userdata) {
    JNIEnv *env;
    jclass classLibspotify = find_class_from_native_thread(&env);
	string &qid = *static_cast<string*>(userdata);
    jstring j_qid = env->NewStringUTF(qid.c_str());
	bool success = (sp_search_error(search) == SP_ERROR_OK) ? true : false;
	int count = sp_search_num_tracks(search);
    jstring j_trackname;
    jstring j_trackuri;
    jstring j_albumname;
    jstring j_artistname;
	sp_track *track;
	for (int i=0;i< count;i++){
	    track = sp_search_track(search, i);
        if (track != 0 && sp_track_error(track) == SP_ERROR_OK){
            const char *temp = sp_track_name(track);
            if (temp != 0 && strlen(temp) != 0){
                j_trackname = env->NewStringUTF(temp);
            }
            int trackDuration = sp_track_duration(track);
            if (sp_track_error(track) != SP_ERROR_OK)
                log("sp_track_error: %s",sp_error_message(sp_track_error(track)));
            int trackDiscnumber = sp_track_disc(track);
            if (sp_track_error(track) != SP_ERROR_OK)
                log("sp_track_error: %s",sp_error_message(sp_track_error(track)));
            int trackIndex = sp_track_index(track);
            if (sp_track_error(track) != SP_ERROR_OK)
                log("sp_track_error: %s",sp_error_message(sp_track_error(track)));
            char buffer [64];
            sp_link *link = sp_link_create_from_track(track, 0);
            if (link != 0){
                sp_link_as_string(link, buffer, 64);
            }
            j_trackuri = env->NewStringUTF(buffer);
            sp_album *album = sp_track_album(track);
            if (sp_track_error(track) != SP_ERROR_OK)
                log("sp_track_error: %s",sp_error_message(sp_track_error(track)));
            int albumYear = 0;
            if (album != 0){
                temp = sp_album_name(album);
                albumYear = sp_album_year(album);
                if (temp != 0 && strlen(temp) != 0){
                    j_albumname = env->NewStringUTF(temp);
                }
            }
            sp_artist *artist = sp_track_artist(track,0);
            if (sp_track_error(track) != SP_ERROR_OK)
                log("sp_track_error: %s",sp_error_message(sp_track_error(track)));
            if (artist != 0){
                temp = sp_artist_name(artist);
                if (temp != 0 && strlen(temp) != 0){
                    j_artistname = env->NewStringUTF(temp);
                }
            }
            jmethodID methodIdAddResult = env->GetStaticMethodID(classLibspotify, "addResult",
                "(Ljava/lang/String;Ljava/lang/String;IIILjava/lang/String;Ljava/lang/String;ILjava/lang/String;)V");
            env->CallStaticVoidMethod(classLibspotify, methodIdAddResult, j_qid, j_trackname,
                trackDuration, trackDiscnumber, trackIndex, j_trackuri,
                j_albumname, albumYear, j_artistname);
            if (env->ExceptionCheck()) {
                env->ExceptionDescribe();
                env->ExceptionClear();
            }
            env->DeleteLocalRef(j_trackname);
            env->DeleteLocalRef(j_trackuri);
            env->DeleteLocalRef(j_artistname);
            env->DeleteLocalRef(j_albumname);
	        j_trackname = NULL;
	        j_trackuri = NULL;
	        j_artistname = NULL;
	        j_albumname = NULL;
        }
	}
    jmethodID methodIdOnResolved = env->GetStaticMethodID(classLibspotify, "onResolved",
	    "(Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V");
    jstring j_error = env->NewStringUTF(sp_error_message(sp_search_error(search)));
    jstring j_didyoumean = env->NewStringUTF(sp_search_did_you_mean(search));
    env->CallStaticVoidMethod(classLibspotify, methodIdOnResolved, j_qid, success, j_error,
        j_didyoumean);
    if (env->ExceptionCheck()) {
        env->ExceptionDescribe();
        env->ExceptionClear();
    }
	env->DeleteLocalRef(classLibspotify);
	env->DeleteLocalRef(j_qid);
	env->DeleteLocalRef(j_error);
	env->DeleteLocalRef(j_didyoumean);

    log("Finished resolving query:'%s', success'%s', track count:'%d', qid:'%s'", sp_search_query(search),
        (success?"true":"false"), count, qid.c_str());
    sp_search_release(search);
    delete &qid;
}
Exemple #19
0
void append_search_tracks(sp_search *search, svn_stringbuf_t *buf) {
  int num_tracks = sp_search_num_tracks(search);

  for (int i = 0; i < num_tracks; i++)
    append_track(sp_search_track(search, i), buf);
}
Exemple #20
0
int Search::trackCount() const
{
    return isValid() ? sp_search_num_tracks(handle()) : 0;
}
void
SpotifySearch::searchComplete( sp_search *result, void *userdata )
{
    UserData* data = reinterpret_cast<UserData*>( userdata );
    qDebug() << "Got search result for qid:" << data->qid;

    // we return the top 50 results for searches, just top 1 for resolve
    QVariantMap resp;
    resp[ "qid" ] = data->qid;
    resp[ "_msgtype" ] = "results";
    QVariantList results;

    // TODO search by popularity!
    qDebug() << "Got num results:" << sp_search_num_tracks( result );
    if( sp_search_num_tracks( result ) > 0 ) {// we have a result
        int num = qMin( sp_search_num_tracks( result ), data->fulltext ? 50 : 1 );
        for( int i = 0; i < num; i++ ) {
            sp_track *const tr = sp_search_track( result, i );
            if( !tr || !sp_track_is_loaded( tr ) ) {
                qDebug() << "Got still loading track, skipping";
                continue;
            }

            sp_link* link  = sp_link_create_from_track( tr, 0 );
            QString uid = data->resolver->addToTrackLinkMap( link );

            int duration = sp_track_duration( tr ) / 1000;
            QVariantMap track;
            track[ "track" ] = QString::fromUtf8( sp_track_name( tr ) );
            track[ "artist" ] = QString::fromUtf8( sp_artist_name( sp_track_artist( tr, 0 ) ) );
            track[ "album" ] = QString::fromUtf8( sp_album_name( sp_track_album( tr ) ) );
            track[ "albumpos" ] = sp_track_index( tr );
            track[ "discnumber"] = sp_track_disc( tr );
            track[ "year" ] = sp_album_year( sp_track_album( tr ) );
            track[ "mimetype" ] = "audio/basic";
            track[ "source" ] = "Spotify";
            track[ "url" ] = QString( "http://localhost:%1/sid/%2.wav" ).arg( data->resolver->port() ).arg( uid );
            track[ "duration" ] = duration;
            track[ "score" ] = .95; // TODO
            track[ "bitrate" ] = 192; // TODO

            // 8 is "magic" number. we don't know how much spotify compresses or in which format (mp3 or ogg) from their server, but 1/8th is approximately how ogg -q6 behaves, so use that for better displaying
            quint32 bytes = ( duration * 44100 * 2 * 2 ) / 8;
            track[ "size" ] = bytes;
            results << track;
            data->searchCount = 0;
            //qDebug() << "Found Track:" << sp_track_name( tr ) << "\n\tReporting:" << track["url"];
        }

    }else
    {
        QString didYouMean = QString::fromUtf8(sp_search_did_you_mean(	result ) );
        if(data->searchCount <= 1  ){
            qDebug() << "Try nr." << data->searchCount << " Searched for" << QString::fromUtf8(sp_search_query(	result ) ) << "Did you mean?"<< didYouMean;
            //int distance = QString::compare(QString::fromUtf8(sp_search_query(	result ) ), QString::fromUtf8(sp_search_did_you_mean(	result ) ), Qt::CaseInsensitive);
            //qDebug() << "Distance for query is " << distance;//if( distance < 4)
            sp_search_create( SpotifySession::getInstance()->Session(), sp_search_did_you_mean(	result ) , 0, data->fulltext ? 50 : 1, 0, 0, 0, 0, &SpotifySearch::searchComplete, data );
            data->searchCount++;
            return;
        }

    }

    resp[ "results" ] = results;
    sp_search_release( result );
    data->resolver->sendMessage( resp );
}