Exemplo n.º 1
0
/*
 * clear search list. Caller must take search_result_lock before calling.
 */
void search_clear()
{
	if(search != NULL)
	{
		sp_search_release(search);
		search = NULL;
	}
}
void QSpotifySearch::clearSearch(sp_search *search)
{
    QMutexLocker lock(&g_mutex);
    if (search)
        sp_search_release(search);
    g_searchObjects.remove(search);
    if (search == m_sp_search)
        m_sp_search = nullptr;
}
Exemplo n.º 3
0
static void send_reply(struct mg_connection *conn) {
  if(!strcmp(conn->uri, "/search")) {
        printf("Received \"search\" request.\n");
        fflush(stdout);

		//mg_printf_data(conn, "Search %s", conn->query_string);
		//Call search function
		
        int isLoaded = 0;
        sp_search* search = sp_search_create(g_sess, conn->query_string, 0, 100, 0, 100, 0, 100, 0, 100, SP_SEARCH_STANDARD, &search_complete, &isLoaded);
		int timeout = 0;
		sp_session_process_events(g_sess, &timeout);
		while(!isLoaded) {
			usleep(100000);
			printf("Waiting...\n");
			sp_session_process_events(g_sess, &timeout);
		}
//    pthread_mutex_lock(&g_search_mutex);

//    while (!isLoaded) {
//    while(!sp_search_is_loaded(search)) {
//        printf("Waiting...\n");
//        fflush(stdout);
//        pthread_cond_wait(&g_search_cond, &g_search_mutex);
//        printConnectionState();
//        print_search_error(search);
//        usleep(1000000);
//    }
//    printf("Received search_complete signal.");
//    fflush(stdout);
    char* rv = search_to_json(search);
//    pthread_mutex_unlock(&g_search_mutex);

        sp_search_release(search);

        mg_printf_data(conn, rv);

	} else if(!strcmp(conn->uri, "/upvote")) {
		mg_printf_data(conn, "Upvote %s", conn->query_string);
		//call upvote function
		mg_printf_data(conn,"Upvoted");
		upvoteHelper(conn->query_string);
		try_playback_start();
	} else if(!strcmp(conn->uri, "/queue")) {
		//call queue function
		// TODO: print this to user not console printf(print_queue());
		mg_printf_data(conn,print_queue());
	} else if(!strcmp(conn->uri, "/key")) {
		//mg_printf_data(conn, "Key: %d", g_appkey[0]);
		// this is not part of our project. it will not be done.
	} else if(!strcmp(conn->uri, "/ping")) {
		mg_printf_data(conn,"Hello. Partyfy is running.");
 	} else {
	}
}
Exemplo n.º 4
0
/**
 * Callback for libspotify
 *
 * @param browse    The browse result object that is now done
 * @param userdata  The opaque pointer given to sp_artistbrowse_create()
 */
static void search_complete(sp_search *search, void *userdata)
{
  if (sp_search_error(search) == SP_ERROR_OK)
    print_search(search);
  else
    fprintf(stderr, "Failed to search: %s\n",
            sp_error_message(sp_search_error(search)));

  sp_search_release(search);
  cmd_done();
}
Exemplo n.º 5
0
Arquivo: main.c Projeto: delrtye/Spot
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);
}
Exemplo n.º 6
0
static void search_complete(sp_search *search, void *userdata)
{


        if (sp_search_error(search) == SP_ERROR_OK){
             get_search(search);
        }
        else cmd_sendresponse(put_error(400, sp_error_message(sp_search_error(search))), 400);

        sp_search_release(search);

        cmd_done();
}
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);
  }
Exemplo n.º 8
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);
}
Exemplo n.º 9
0
void sess_init(struct event_base *evbase)
{
  g_session.evbase  = evbase;
  g_session.spot_ev = evtimer_new(evbase, sess_event_cb, &g_session);
  g_session.stop_ev = evtimer_new(evbase, sess_stop_cb, &g_session);
  g_session.exiting = false;
  g_session.current_track = NULL;

  sp_session_config config = {
    .api_version          = SPOTIFY_API_VERSION,
    .cache_location       = "tmp",
    .settings_location    = "tmp",
    .application_key      = g_appkey,
    .application_key_size = g_appkey_size,
    .user_agent           = POLSPOT_USER_AGENT,
    .callbacks            = &g_callbacks,
    .userdata             = &g_session
  };

  sp_error err = sp_session_init(&config, &g_session.spotify);

  if (err != SP_ERROR_OK)
    panic("sp_session_init() failed: %s", sp_error_message(err));
}

void sess_cleanup()
{
  // If user is logged in then initiate logout. This will change the session
  // state to SESS_DISCONNECTING. Another call to this function will thus exit
  // the main loop without waiting for the logout process to finish, allowing
  // users to avoid waiting for timeouts by issuing the quit commant twice.
  if (g_session.state == SESS_ONLINE) {
    sess_disconnect();
    g_session.exiting = true;
  }
  else {
    free(g_session.username);
    g_session.username = 0;
    free(g_session.password);
    g_session.password = 0;

    // Free search results.
    for (sess_search_t *s = g_session.search; s;) {
      sp_search_release(s->res);
      sess_search_t *p = s;
      s = s->next;
      free(p);
    }

    g_session.current_track = NULL;
    event_free(g_session.spot_ev);

    // Exit main event loop.
    event_base_loopbreak(g_session.evbase);
  }
}

void sess_connect()
{
  assert(g_session.username && g_session.password);

  sess_disconnect();

  // Login with credentials set by sess_username/sess_password.
  sp_error err = sp_session_login(g_session.spotify, g_session.username, g_session.password);

  if (err != SP_ERROR_OK)
    panic("sp_session_login() failed: %s", sp_error_message(err));

  log_append("Connecting...");

  // Redraw status info.
  g_session.state = SESS_CONNECTING;
  ui_dirty(UI_FOOTER);
  ui_update_post(0);
}
Exemplo n.º 10
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;
}
Exemplo n.º 11
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 );
}