Skip to content

Commit

Permalink
Handle spotify login better
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobobryant committed Aug 30, 2017
1 parent 8482074 commit 6cec80b
Show file tree
Hide file tree
Showing 5 changed files with 163 additions and 12 deletions.
12 changes: 12 additions & 0 deletions reco/src/reco/reco.clj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
[set_last_event_id [long] void]
[session_size [] int]
[update_freshness [java.util.Collection java.util.Collection] void]
[refresh_candidates [java.util.Collection] boolean]
^:static [calc_strength [java.util.Collection] double]
^:static [modelify [java.util.Collection long] java.util.Map]
^:static [modelify [java.util.Collection long java.util.Collection String] java.util.Map]
Expand Down Expand Up @@ -327,6 +328,17 @@
input-data (map-indexed get-deltas event-vec)]
(apply min-key #(total-error input-data %) strength-set)))

(defn -refresh_candidates [this library]
(println "refreshing candidates")
(let [candidates (into {} (map (fn [song] [(get song "_id")
(Candidate. 1 0 0 0 1 1 1)])
library))
old-count (count (:candidates @@this))]
(swap! (.state this)
(fn [state]
(update state :candidates #(merge candidates %))))
(> (count (:candidates @@this)) old-count)))

(defn -parse_top_tracks [response]
(let [data (json/read-str response)]
(map (fn [item] {"spotify_id" (get item "uri")
Expand Down
89 changes: 87 additions & 2 deletions src/com/jacobobryant/moody/Moody.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import com.jacobobryant.moody.vanilla.PrefKeys;
import com.jacobobryant.moody.vanilla.Song;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
Expand All @@ -44,7 +45,7 @@ public class Moody {

private Moody() { }

public static Moody getInstance(Context context,
public synchronized static Moody getInstance(Context context,
InitProgressListener listener) {
if (instance == null) {
Log.d(C.TAG, "package name:" + context.getPackageName());
Expand All @@ -55,7 +56,7 @@ public static Moody getInstance(Context context,
return instance;
}

public static Moody getInstance(Context context) {
public synchronized static Moody getInstance(Context context) {
return getInstance(context, new InitProgressListener() {
@Override
public void update(String s) { }
Expand Down Expand Up @@ -179,6 +180,15 @@ private void init(InitProgressListener listener) {
Log.d(C.TAG, "finished moody.init()");
}

public boolean refresh_candidates() {
SQLiteDatabase db = new Database(context).getReadableDatabase();
boolean ret = rec.refresh_candidates(cursor_to_maps(
db.rawQuery("SELECT _id, artist, album, title, source, " +
"spotify_id, duration, mem_strength FROM songs", null)));
db.close();
return ret;
}

public Map get_model(SQLiteDatabase db, long id, String artist) {
List song_model = cursor_to_maps(db.rawQuery(
"select id_a, id_b, score from model where id_a = ?1 or id_b = ?1",
Expand Down Expand Up @@ -326,12 +336,14 @@ public Metadata pick_next(boolean local_only) {
public static void add_to_library(Context c, List<Metadata> songs) {
SQLiteDatabase db = new Database(c).getWritableDatabase();
db.beginTransaction();
int count = 0;
for (Metadata s : songs) {
String query = "select _id, source from songs where " + match_clause(s);
Cursor result = db.rawQuery(query, s.query());

result.moveToFirst();
if (result.getCount() == 0) {
count++;
db.execSQL("INSERT INTO songs (artist, album, title, duration, source, spotify_id) " +
"VALUES (?, ?, ?, ?, ?, ?)",
new String[] {s.artist, s.album, s.title, String.valueOf(s.duration),
Expand All @@ -346,6 +358,7 @@ public static void add_to_library(Context c, List<Metadata> songs) {
db.setTransactionSuccessful();
db.endTransaction();
db.close();
Log.d(C.TAG, "added " + count + " songs to library");
}

private static String match_clause(Metadata s) {
Expand Down Expand Up @@ -406,10 +419,78 @@ public static boolean spotify_token_expired(Context context) {
settings.getLong(PrefKeys.SPOTIFY_TOKEN_EXPIRATION, 0);
}

public static boolean wants_spotify(Context context) {
SharedPreferences settings = PlaybackService.getSettings(context);
return settings.getBoolean(PrefKeys.WANTS_SPOTIFY, false);
}

public static boolean already_asked_about_spotify(Context context) {
SharedPreferences settings = PlaybackService.getSettings(context);
return settings.getBoolean(PrefKeys.ALREADY_ASKED, false);
}

public static void set_already_asked(Context context) {
SharedPreferences.Editor editor =
PlaybackService.getSettings(context).edit();
editor.putBoolean(PrefKeys.ALREADY_ASKED, true);
editor.commit();
}

public static void wants_spotify(Context context, boolean wants) {
SharedPreferences.Editor editor =
PlaybackService.getSettings(context).edit();
editor.putBoolean(PrefKeys.WANTS_SPOTIFY, wants);
editor.commit();
}

public void add_to_blacklist(long id) {
rec.add_to_blacklist(id);
}

public static class SpotifyTask extends AsyncTask<Void, String, Void> {
ProgressDialog dialog;
Context c;
NaviListener navi;

public SpotifyTask(Context c, NaviListener navi) {
super();
this.dialog = new ProgressDialog(c);
this.c = c;
this.navi = navi;
dialog.setTitle("Getting Spotify songs");
dialog.setCancelable(false);
dialog.show();
}

@Override
protected Void doInBackground(Void... v) {
Log.d(C.TAG, "doing SpotifyTask");
try {
SyncAdapter.getSpotifySongs(this.c);
Moody.getInstance(this.c, new InitProgressListener() {
public void update(String s) {
publishProgress(s);
}
}).refresh_candidates();
navi.hey_listen();
} catch (IOException e) {
Log.e(C.TAG, "couldn't get spotify songs", e);
}
Log.d(C.TAG, "finished SpotifyTask");
return null;
}

@Override
protected void onPostExecute(Void v) {
dialog.dismiss();
}

@Override
protected void onProgressUpdate(String... s) {
dialog.setMessage(s[0]);
}
}

public static class InitTask extends AsyncTask<Void, String, Void> {
ProgressDialog dialog;
Context c;
Expand Down Expand Up @@ -447,4 +528,8 @@ protected void onPostExecute(Void v) {
interface InitProgressListener {
void update(String foo);
}

public interface NaviListener {
void hey_listen();
}
}
12 changes: 6 additions & 6 deletions src/com/jacobobryant/moody/SyncAdapter.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ public void onPerformSync(Account account, Bundle extras, String authority,
Log.d(C.TAG, "onPerformSync()");
syncDb(context);
getSpotifySongs(context);
getSpotifyIds(context);
getSpotifyFeatures(context);
//getSpotifyIds(context);
//getSpotifyFeatures(context);
} catch (Exception e) {
//ACRA.getErrorReporter().handleException(e);
Log.e(C.TAG, "couldn't finish sync stuff", e);
Expand Down Expand Up @@ -125,7 +125,7 @@ public static void syncDb(Context context) {
}
}

public void getSpotifySongs(Context context) throws IOException {
public static void getSpotifySongs(Context context) throws IOException {
// get spotify songs
if (Moody.spotify_token_expired(context)) {
return;
Expand Down Expand Up @@ -153,7 +153,7 @@ public void getSpotifySongs(Context context) throws IOException {
Log.d(C.TAG, "finished spotify thang");
}

public void getSpotifyIds(Context context) throws IOException {
public static void getSpotifyIds(Context context) throws IOException {
if (Moody.spotify_token_expired(context)) {
return;
}
Expand Down Expand Up @@ -214,7 +214,7 @@ public void getSpotifyIds(Context context) throws IOException {
Log.d(C.TAG, "finished getSpotifyIds()");
}

private String get_search_query(String artist, String album, String title)
private static String get_search_query(String artist, String album, String title)
throws UnsupportedEncodingException, MalformedURLException {
StringBuilder query = new StringBuilder();
query.append("https://api.spotify.com/v1/search?type=track&q=");
Expand All @@ -231,7 +231,7 @@ private String get_search_query(String artist, String album, String title)
return query.toString();
}

private class GetIdTask extends AsyncTask<Void, Void, Void> {
private static class GetIdTask extends AsyncTask<Void, Void, Void> {
private URL url;
private String token;
private int row_id;
Expand Down
60 changes: 56 additions & 4 deletions src/com/jacobobryant/moody/vanilla/LibraryActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,13 @@ protected void onActivityResult(int requestCode, int resultCode, Intent intent)
.putLong(PrefKeys.SPOTIFY_TOKEN_EXPIRATION,
response.getExpiresIn() + System.currentTimeMillis() / 1000)
.commit();
new Moody.SpotifyTask(this, new Moody.NaviListener() {
@Override
public void hey_listen() {
LibraryActivity.this.finish();
LibraryActivity.this.startActivity(LibraryActivity.this.getIntent());
}
}).execute();
break;
case ERROR:
Log.e(C.TAG, "Uh oh, Spotify auth error: " + response.getError());
Expand Down Expand Up @@ -317,7 +324,8 @@ public void onResume() {
registerReceiver(mPluginInfoReceiver, new IntentFilter(PluginUtils.ACTION_HANDLE_PLUGIN_PARAMS));

if (PermissionRequestActivity.havePermissions(this)) {
if (Moody.spotify_token_expired(this)) {
Log.d(C.TAG, "got permission");
if (Moody.wants_spotify(this) && Moody.spotify_token_expired(this)) {
Log.d(C.TAG, "refreshing spotify token");
AuthenticationRequest.Builder builder =
new AuthenticationRequest.Builder(C.CLIENT_ID,
Expand All @@ -326,10 +334,39 @@ public void onResume() {
"user-top-read"});
AuthenticationRequest request = builder.build();
AuthenticationClient.openLoginActivity(this, 666, request);
} else if (!Moody.already_asked_about_spotify(this)) {
Log.d(C.TAG, "doing that alert thang");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Do you have a Spotify premium account?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Moody.set_already_asked(LibraryActivity.this);
Moody.wants_spotify(LibraryActivity.this, true);
Log.d(C.TAG, "getting spotify token");
AuthenticationRequest.Builder builder =
new AuthenticationRequest.Builder(C.CLIENT_ID,
AuthenticationResponse.Type.TOKEN, C.REDIRECT_URI);
builder.setScopes(new String[]{"user-read-private", "streaming",
"user-top-read"});
AuthenticationRequest request = builder.build();
AuthenticationClient.openLoginActivity(LibraryActivity.this, 666, request);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Moody.set_already_asked(LibraryActivity.this);
Moody.wants_spotify(LibraryActivity.this, false);
new Moody.InitTask(LibraryActivity.this).execute();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
Log.d(C.TAG, "spotify token is still valid");
new Moody.InitTask(this).execute();
}
} else {
Log.d(C.TAG, "no permissions");
}
Log.d(C.TAG, "finished LibraryActivity.onResume()");
}
Expand Down Expand Up @@ -900,8 +937,10 @@ public boolean onCreateOptionsMenu(Menu menu)
menu.add(0, MENU_SORT, 30, R.string.sort_by).setIcon(R.drawable.ic_menu_sort_alphabetically);
if (BuildConfig.DEBUG) {
menu.add(0, MENU_MOOD, 0, "New session");
menu.add(0, MENU_TEST, 0, "Test");
//menu.add(0, MENU_TEST, 0, "Test");
}
String title = (Moody.wants_spotify(this)) ? "Disable Spotify" : "Login to Spotify";
menu.add(0, MENU_TEST, 0, title);
return true;
}

Expand All @@ -918,8 +957,21 @@ public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case MENU_TEST:
Intent intent = new Intent(this, SpotifyActivity.class);
startActivity(intent);
Moody.set_already_asked(this);
boolean wants = !Moody.wants_spotify(this);
Moody.wants_spotify(this, wants);
if (wants) {
Moody.wants_spotify(this, true);
Log.d(C.TAG, "getting spotify token");
AuthenticationRequest.Builder bob_builder =
new AuthenticationRequest.Builder(C.CLIENT_ID,
AuthenticationResponse.Type.TOKEN, C.REDIRECT_URI);
bob_builder.setScopes(new String[]{"user-read-private", "streaming",
"user-top-read"});
AuthenticationRequest request = bob_builder.build();
AuthenticationClient.openLoginActivity(LibraryActivity.this, 666, request);
}
return true;
case MENU_MOOD:
//Moody.getInstance(this).rec.new_session();
//final String[] moods = new String[] { "mood 1", "mood 2", "mood 3",
Expand Down
2 changes: 2 additions & 0 deletions src/com/jacobobryant/moody/vanilla/PrefKeys.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,6 @@ public class PrefKeys {
public static final String SPOTIFY_TOKEN = "spotify_token";
public static final String SPOTIFY_TOKEN_EXPIRATION = "spotify_token_expiration";
public static final String LAST_EVENT_IN_MODEL = "last_event_in_model";
public static final String WANTS_SPOTIFY = "wants_spotify";
public static final String ALREADY_ASKED = "already_asked";
}

0 comments on commit 6cec80b

Please sign in to comment.