diff --git a/.gitignore b/.gitignore index a22392ade60e..ea5d367f0609 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ /bin /gen +local.properties +res/raw/config.properties diff --git a/AndroidManifest.xml b/AndroidManifest.xml index b1c515c2c280..88d02bb254f9 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -150,6 +150,10 @@ android:configChanges="orientation|keyboardHidden|screenSize" android:launchMode="singleTask" > + + + + + + + + \ No newline at end of file diff --git a/res/layout/notifications.xml b/res/layout/notifications.xml new file mode 100644 index 000000000000..7141b33eaaf1 --- /dev/null +++ b/res/layout/notifications.xml @@ -0,0 +1,17 @@ + + + + + + \ No newline at end of file diff --git a/res/raw/config.properties.sample b/res/raw/config.properties.sample new file mode 100644 index 000000000000..68c5bb09209f --- /dev/null +++ b/res/raw/config.properties.sample @@ -0,0 +1,5 @@ +# Add your WordPress App credentials here +# Get you App ID from http://developer.wordpress.com +oauth.app_id= +oauth.app_secret= +oauth.redirect_uri= diff --git a/res/values/strings.xml b/res/values/strings.xml index 403456921072..f6e17426a0fa 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -317,6 +317,9 @@ Reader Topics + + + Notifications diff --git a/src/org/wordpress/android/WordPress.java b/src/org/wordpress/android/WordPress.java index 72886d5a8124..4fa2fd80143d 100644 --- a/src/org/wordpress/android/WordPress.java +++ b/src/org/wordpress/android/WordPress.java @@ -1,7 +1,9 @@ package org.wordpress.android; +import java.io.InputStream; import java.util.List; import java.util.Map; +import java.util.Properties; import android.app.Application; import android.content.SharedPreferences; @@ -9,10 +11,12 @@ import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.preference.PreferenceManager; +import android.util.Log; import org.wordpress.android.models.Blog; import org.wordpress.android.models.Comment; import org.wordpress.android.models.Post; +import org.wordpress.android.util.WPRestClient; public class WordPress extends Application { @@ -24,16 +28,22 @@ public class WordPress extends Application { public static OnPostUploadedListener onPostUploadedListener = null; public static boolean postsShouldRefresh; public static boolean shouldRestoreSelectedActivity; + public static WPRestClient restClient; + public static Properties config; + + public static final String TAG="WordPress"; @Override public void onCreate() { + loadProperties(); versionName = getVersionName(); wpDB = new WordPressDB(this); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); if (settings.getInt("wp_pref_last_activity", -1) >= 0) shouldRestoreSelectedActivity = true; - + + restClient = new WPRestClient(config, settings); super.onCreate(); } @@ -153,4 +163,17 @@ public static Blog setCurrentBlog(int id) { return currentBlog; } + /** + * Load res/raw/config.properties into a Properties object + */ + private void loadProperties(){ + config = new Properties(); + InputStream stream = getResources().openRawResource(R.raw.config); + try { + config.load(stream); + } catch(java.io.IOException error){ + config = null; + Log.e(TAG, "Could not load config.properties", error); + } + } } diff --git a/src/org/wordpress/android/models/Note.java b/src/org/wordpress/android/models/Note.java new file mode 100644 index 000000000000..3602a9c9ed08 --- /dev/null +++ b/src/org/wordpress/android/models/Note.java @@ -0,0 +1,147 @@ +/** + * Note represents a single WordPress.com notification + */ +package org.wordpress.android.models; + +import android.text.Html; +import android.util.Log; + +import org.json.JSONObject; +import org.json.JSONArray; +import org.json.JSONException; + +public class Note { + protected static final String TAG="NoteModel"; + public static final String UNKNOWN_TYPE="unknown"; + public static final String COMMENT_TYPE="comment"; + public static final String LIKE_TYPE="like"; + + private static String QUERY_SEPERATOR="."; + private static String QUERY_ARRAY_INDEX_START="["; + private static String QUERY_ARRAY_INDEX_END="]"; + private static String QUERY_ARRAY_FIRST="first"; + private static String QUERY_ARRAY_LAST="last"; + + private JSONObject mNoteJSON; + /** + * Create a note using JSON from REST API + */ + public Note(JSONObject noteJSON){ + mNoteJSON = noteJSON; + Log.d(TAG, String.format("Built note of type: %s", getType())); + } + + public String toString(){ + String labelText = queryJSON("subject.text", ""); + String label = Html.fromHtml(labelText.trim()).toString(); + return label; + } + + public JSONObject toJSONObject(){ + return mNoteJSON; + } + + public String getType(){ + return queryJSON("type", UNKNOWN_TYPE); + } + public Boolean isType(String type){ + return getType().equals(type); + } + public Boolean isCommentType(){ + return isType(COMMENT_TYPE); + } + public String getIconURL(){ + return (String) queryJSON("subject.icon", ""); + } + protected Object queryJSON(String query){ + Object defaultObject = ""; + return queryJSON(query, defaultObject); + } + /** + * Rudimentary system for pulling an item out of a JSON object hierarchy + */ + public U queryJSON(String query, U defaultObject){ + int offset = 0; + JSONObject queryJSON = mNoteJSON; + do { + // find the next . or [ + int next_seperator = query.indexOf(QUERY_SEPERATOR, offset); + boolean has_next_seperator = next_seperator > -1; + int start_array = query.indexOf(QUERY_ARRAY_INDEX_START, offset); + // pull out the key up to the seperator + if (next_seperator == -1 && start_array == -1) { + try { + return (U) queryJSON.get(query.substring(offset)); + } catch (JSONException e) { + Log.e(TAG, String.format("Failed to query %s", query), e); + return defaultObject; + } + } + String key; + if (start_array == -1 || (next_seperator > -1 && start_array > next_seperator )) { + try { + queryJSON = queryJSON.getJSONObject(query.substring(offset, next_seperator)); + } catch (JSONException e) { + Log.e(TAG, String.format("Failed to query key %s", query), e); + return defaultObject; + } + offset = next_seperator+1; + continue; + } + if (next_seperator == -1 || start_array == -1) { + key = query.substring(offset, Math.max(next_seperator, start_array)); + } else { + key = query.substring(offset, Math.min(next_seperator, start_array)); + } + if (start_array > -1 && (start_array < next_seperator || !has_next_seperator)) { + // time to pull off arrays + try { + JSONArray arrayJSON = queryJSON.getJSONArray(key); + do { + int end_array = query.indexOf(QUERY_ARRAY_INDEX_END, start_array); + if (end_array <= start_array) break; + offset = end_array; + String index = query.substring(start_array+1, end_array); + int i; + if (index.equals(QUERY_ARRAY_FIRST)) { + i = 0; + } else if (index.equals(QUERY_ARRAY_LAST)) { + i = -1; + } else { + i = Integer.parseInt(index); + } + if (i < 0) + i = arrayJSON.length() + i; + start_array = query.indexOf(QUERY_ARRAY_INDEX_START, end_array); + // no more arrays and no seperator, end of query, return object at index + // e.g. key[0][0] + if (start_array == -1 && !has_next_seperator) { + return (U) arrayJSON.get(i); + } + // no more arrays but there's a seperator, we must have a JSONObject + if (start_array == -1 && has_next_seperator) { + queryJSON = arrayJSON.getJSONObject(i); + break; + } + // theres more query but this is the last array in this section + // eg key[0][0][0].something[0] + arrayJSON = arrayJSON.getJSONArray(i); + // the next item is an array, so pull the array off and continue + } while(start_array < next_seperator); + offset = next_seperator + 1; + continue; + } catch (JSONException e) { + Log.e(TAG, String.format("Failed to query array %s", query), e); + return defaultObject; + } + } + Log.d(TAG, String.format("We need to remove the key from %s", query.substring(offset, next_seperator))); + key = query.substring(offset, next_seperator); + + if(true) return defaultObject; + + } while(offset > 0); + return defaultObject; + } + +} \ No newline at end of file diff --git a/src/org/wordpress/android/ui/WPActionBarActivity.java b/src/org/wordpress/android/ui/WPActionBarActivity.java index 1011d79dc7f6..7ed784834832 100644 --- a/src/org/wordpress/android/ui/WPActionBarActivity.java +++ b/src/org/wordpress/android/ui/WPActionBarActivity.java @@ -53,6 +53,7 @@ import org.wordpress.android.ui.posts.PostsActivity; import org.wordpress.android.ui.prefs.PreferencesActivity; import org.wordpress.android.ui.reader.ReaderActivity; +import org.wordpress.android.ui.notifications.NotificationsActivity; import org.wordpress.android.util.EscapeUtils; /** @@ -85,6 +86,7 @@ public abstract class WPActionBarActivity extends SherlockFragmentActivity { protected static final int VIEW_SITE_ACTIVITY = 7; protected static final int DASHBOARD_ACTIVITY = 8; protected static final int SETTINGS_ACTIVITY = 9; + protected static final int NOTIFICATIONS_ACTIVITY = 10; protected static final String LAST_ACTIVITY_PREFERENCE = "wp_pref_last_activity"; @@ -102,13 +104,48 @@ public abstract class WPActionBarActivity extends SherlockFragmentActivity { private List mMenuItems = new ArrayList(); private ListView mListView; private IcsSpinner mBlogSpinner; - + private boolean mFirstLaunch = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4) mIsXLargeDevice = true; + // configure all the available menu items + mMenuItems.add(new NotificationsMenuItem()); + mMenuItems.add(new ReaderMenuItem()); + mMenuItems.add(new PostsMenuItem()); + mMenuItems.add(new PagesMenuItem()); + mMenuItems.add(new CommentsMenuItem()); + mMenuItems.add(new StatsMenuItem()); + mMenuItems.add(new QuickPhotoMenuItem()); + mMenuItems.add(new QuickVideoMenuItem()); + mMenuItems.add(new ViewSiteMenuItem()); + mMenuItems.add(new AdminMenuItem()); + mMenuItems.add(new SettingsMenuItem()); + + // Restore last selection on app creation + // TODO: This more likely belongs in WPActionBarActivity + if (WordPress.shouldRestoreSelectedActivity && WordPress.getCurrentBlog() != null + && !(this instanceof PagesActivity)) { + WordPress.shouldRestoreSelectedActivity = false; + SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); + int lastActivitySelection = settings.getInt(LAST_ACTIVITY_PREFERENCE, -1); + if (lastActivitySelection > MenuDrawerItem.NO_ITEM_ID) { + Iterator itemIterator = mMenuItems.iterator(); + while(itemIterator.hasNext()){ + MenuDrawerItem item = itemIterator.next(); + // if we have a matching item id, and it's not selected and it's visible, call it + if (item.hasItemId() && item.getItemId() == lastActivitySelection && !item.isSelected() && item.isVisible()) { + mFirstLaunch = true; + Log.d(TAG, String.format("Switch to %d", item.getItemId())); + item.selectItem(); + finish(); + break; + } + } + } + } } @Override @@ -252,20 +289,6 @@ public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCoun mMenuDrawer.setMenuView(mListView); mListView.setAdapter(mAdapter); - - // configure all the available menu items - // mMenuItems.add(new NotificationsMenuItem()); - mMenuItems.add(new ReaderMenuItem()); - mMenuItems.add(new PostsMenuItem()); - mMenuItems.add(new PagesMenuItem()); - mMenuItems.add(new CommentsMenuItem()); - mMenuItems.add(new StatsMenuItem()); - mMenuItems.add(new QuickPhotoMenuItem()); - mMenuItems.add(new QuickVideoMenuItem()); - mMenuItems.add(new ViewSiteMenuItem()); - mMenuItems.add(new AdminMenuItem()); - mMenuItems.add(new SettingsMenuItem()); - updateMenuDrawer(); } @@ -298,6 +321,11 @@ protected void startActivityWithDelay(final Intent i) { // Tablets in landscape don't need a delay because the menu drawer doesn't close startActivity(i); } else { + // When switching to LAST_ACTIVITY_PREFERENCE onCreate we don't need to delay + if (mFirstLaunch) { + startActivity(i); + return; + } // Let the menu animation finish before starting a new activity new Handler().postDelayed(new Runnable() { @Override @@ -513,6 +541,26 @@ public boolean onOptionsItemSelected(MenuItem item) { */ public void onBlogChanged() { WordPress.wpDB.updateLastBlogId(WordPress.currentBlog.getId()); + // the menu may have changed, we need to change the selection if the selected item + // is not available in the menu anymore + Iterator itemIterator = mMenuItems.iterator(); + while(itemIterator.hasNext()){ + MenuDrawerItem item = itemIterator.next(); + // if the item is selected, but it's no longer visible we need to + // select the first available item from the adapter + if (item.isSelected() && !item.isVisible()) { + // then select the first item and activate it + mAdapter.getItem(0).selectItem(); + // if it has an item id save it to the preferences + if (item.hasItemId()){ + SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(WPActionBarActivity.this); + SharedPreferences.Editor editor = settings.edit(); + editor.putInt(LAST_ACTIVITY_PREFERENCE, item.getItemId()); + editor.commit(); + } + break; + } + } } public void startAnimatingRefreshButton(MenuItem refreshItem) { @@ -762,4 +810,25 @@ public void onSelectItem(){ startActivityForResult(settingsIntent, SETTINGS_REQUEST); } } + private class NotificationsMenuItem extends MenuDrawerItem { + NotificationsMenuItem(){ + super(NOTIFICATIONS_ACTIVITY, R.string.notifications, R.drawable.dashboard_icon_comments); + } + @Override + public Boolean isVisible(){ + return WordPress.currentBlog != null && WordPress.currentBlog.isDotcomFlag(); + } + @Override + public Boolean isSelected(){ + return WPActionBarActivity.this instanceof NotificationsActivity; + } + @Override + public void onSelectItem(){ + if (!(WPActionBarActivity.this instanceof NotificationsActivity)) + mShouldFinish = true; + Intent intent = new Intent(WPActionBarActivity.this, NotificationsActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + startActivityWithDelay(intent); + } + } } diff --git a/src/org/wordpress/android/ui/notifications/NotificationsActivity.java b/src/org/wordpress/android/ui/notifications/NotificationsActivity.java new file mode 100644 index 000000000000..49740d4290ea --- /dev/null +++ b/src/org/wordpress/android/ui/notifications/NotificationsActivity.java @@ -0,0 +1,133 @@ +package org.wordpress.android.ui.notifications; + +import java.util.List; +import java.util.ArrayList; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.os.Bundle; +import android.util.Log; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentTransaction; +import android.text.Html; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ListAdapter; +import android.widget.ArrayAdapter; +import android.widget.TextView; +import android.widget.ImageView; + +import com.actionbarsherlock.app.ActionBar; +import com.actionbarsherlock.view.Menu; +import com.actionbarsherlock.view.MenuInflater; +import com.actionbarsherlock.view.MenuItem; + +import org.wordpress.android.R; +import org.wordpress.android.ui.WPActionBarActivity; +import org.wordpress.android.models.Blog; +import org.wordpress.android.models.Note; +import static org.wordpress.android.WordPress.*; + +import com.wordpress.rest.OauthTokenResponseHandler; +import com.wordpress.rest.OauthToken; +import com.loopj.android.http.JsonHttpResponseHandler; + +import org.json.JSONObject; +import org.json.JSONArray; +import org.json.JSONException; + +public class NotificationsActivity extends WPActionBarActivity { + public final String TAG="WPNotifications"; + + private NotificationsListFragment mNotesList; + + @Override + public void onCreate(Bundle savedInstanceState){ + super.onCreate(savedInstanceState); + createMenuDrawer(R.layout.notifications); + + ActionBar actionBar = getSupportActionBar(); + actionBar.setDisplayShowTitleEnabled(true); + setTitle(getString(R.string.notifications)); + + FragmentManager fm = getSupportFragmentManager(); + mNotesList = (NotificationsListFragment) fm.findFragmentById(R.id.notes_list); + + Blog blog = getCurrentBlog(); + + // ok it's time to request notifications + // TODO: access token should be stored in preferences, not fetched each time + restClient.requestAccessToken(blog.getUsername(), blog.getPassword(), new OauthTokenResponseHandler(){ + @Override + public void onStart(){ + Log.d(TAG, "Requesting token"); + } + @Override + public void onSuccess(OauthToken token){ + refreshNotes(); + } + @Override + public void onFailure(Throwable e, JSONObject response){ + Log.e(TAG, String.format("Failed: %s", response), e); + } + @Override + public void onFinish(){ + Log.d(TAG, "Done requesting token"); + } + }); + } + + public void refreshNotes(){ + restClient.getNotifications(new JsonHttpResponseHandler(){ + @Override + public void onSuccess(int responseCode, JSONObject response) { + try { + JSONArray notesJSON = response.getJSONArray("notes"); + final List notesList = new ArrayList(notesJSON.length()); + for (int i=0; i notes){ + // create a new ListAdapter and set it on the fragment + ListAdapter adapter = new NotesAdapter(notes); + mNotesList.setListAdapter(adapter); + } + + private class NotesAdapter extends ArrayAdapter { + NotesAdapter(List notes){ + super(NotificationsActivity.this, R.layout.note_list_item, R.id.note_label, notes); + } + @Override + public View getView(int position, View convertView, ViewGroup parent){ + View view = super.getView(position, convertView, parent); + final Note note = getItem(position); + TextView detailText = (TextView) view.findViewById(R.id.note_detail); + if (note.isCommentType()) { + detailText.setText(Html.fromHtml(note.queryJSON("body.items[last].html", "Couldn't find note body")).toString().trim()); + detailText.setVisibility(View.VISIBLE); + } else { + detailText.setVisibility(View.GONE); + } + final ImageView iconView = (ImageView) view.findViewById(R.id.note_icon); + iconView.setImageResource(R.drawable.placeholder); + iconView.setTag(note.getIconURL()); + return view; + } + } +} diff --git a/src/org/wordpress/android/ui/notifications/NotificationsListFragment.java b/src/org/wordpress/android/ui/notifications/NotificationsListFragment.java new file mode 100644 index 000000000000..7adf624ae9b3 --- /dev/null +++ b/src/org/wordpress/android/ui/notifications/NotificationsListFragment.java @@ -0,0 +1,28 @@ +package org.wordpress.android.ui.notifications; + +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentTransaction; +import android.support.v4.app.ListFragment; +import android.widget.ListAdapter; + +import org.wordpress.android.R; + +import com.commonsware.cwac.cache.SimpleWebImageCache; +import com.commonsware.cwac.thumbnail.ThumbnailAdapter; +import com.commonsware.cwac.thumbnail.ThumbnailBus; +import com.commonsware.cwac.thumbnail.ThumbnailMessage; + +public class NotificationsListFragment extends ListFragment { + private static final int[] IMAGE_IDS={ R.id.note_icon }; + @Override + public void setListAdapter(ListAdapter adapter){ + // Wrap the adapter in the thumbnail adapter + ThumbnailBus bus = new ThumbnailBus(); + SimpleWebImageCache cache; + cache = new SimpleWebImageCache(null, null, 101, bus); + ThumbnailAdapter thumbAdapter = new ThumbnailAdapter( getActivity(), adapter, cache, IMAGE_IDS); + super.setListAdapter(thumbAdapter); + + } + +} \ No newline at end of file diff --git a/src/org/wordpress/android/ui/posts/PostsActivity.java b/src/org/wordpress/android/ui/posts/PostsActivity.java index a7cc3ceda6a0..a9666096ea20 100644 --- a/src/org/wordpress/android/ui/posts/PostsActivity.java +++ b/src/org/wordpress/android/ui/posts/PostsActivity.java @@ -31,16 +31,11 @@ import org.wordpress.android.R; import org.wordpress.android.WordPress; import org.wordpress.android.models.Post; -import org.wordpress.android.ui.DashboardActivity; -import org.wordpress.android.ui.StatsActivity; -import org.wordpress.android.ui.ViewSiteActivity; import org.wordpress.android.ui.WPActionBarActivity; -import org.wordpress.android.ui.comments.CommentsActivity; import org.wordpress.android.ui.posts.ViewPostFragment.OnDetailPostActionListener; import org.wordpress.android.ui.posts.ViewPostsFragment.OnPostActionListener; import org.wordpress.android.ui.posts.ViewPostsFragment.OnPostSelectedListener; import org.wordpress.android.ui.posts.ViewPostsFragment.OnRefreshListener; -import org.wordpress.android.ui.reader.ReaderActivity; import org.wordpress.android.util.WPAlertDialogFragment.OnDialogConfirmListener; public class PostsActivity extends WPActionBarActivity implements OnPostSelectedListener, @@ -60,42 +55,6 @@ public class PostsActivity extends WPActionBarActivity implements OnPostSelected public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - // Restore last selection on app creation - if (WordPress.shouldRestoreSelectedActivity && WordPress.getCurrentBlog() != null - && !(this instanceof PagesActivity)) { - WordPress.shouldRestoreSelectedActivity = false; - SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); - int lastActivitySelection = settings.getInt("wp_pref_last_activity", -1); - if (lastActivitySelection >= 0) { - Intent i = null; - switch (lastActivitySelection) { - case READER_ACTIVITY: - i = new Intent(this, ReaderActivity.class); - break; - case PAGES_ACTIVITY: - i = new Intent(this, PagesActivity.class); - i.putExtra("viewPages", true); - break; - case COMMENTS_ACTIVITY: - i = new Intent(this, CommentsActivity.class); - break; - case STATS_ACTIVITY: - i = new Intent(this, StatsActivity.class); - break; - case VIEW_SITE_ACTIVITY: - i = new Intent(this, ViewSiteActivity.class); - break; - case DASHBOARD_ACTIVITY: - i = new Intent(this, DashboardActivity.class); - break; - } - if (i != null) { - startActivity(i); - finish(); - } - } - } - createMenuDrawer(R.layout.posts); ActionBar actionBar = getSupportActionBar(); diff --git a/src/org/wordpress/android/ui/reader/ReaderActivity.java b/src/org/wordpress/android/ui/reader/ReaderActivity.java index c26b1a629eb1..8a2fd5f6a820 100644 --- a/src/org/wordpress/android/ui/reader/ReaderActivity.java +++ b/src/org/wordpress/android/ui/reader/ReaderActivity.java @@ -449,17 +449,6 @@ public void onBlogChanged() { if (WordPress.currentBlog.isDotcomFlag()) { ReaderImplFragment readerPageFragment = (ReaderImplFragment) readerPage; readerPageFragment.reloadReader(); - } else { - // Self-hosted blogs do not have Reader access, send to posts instead - SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ReaderActivity.this); - SharedPreferences.Editor editor = settings.edit(); - editor.putInt("wp_pref_last_activity", POSTS_ACTIVITY); - editor.commit(); - mShouldFinish = true; - Intent i = new Intent(ReaderActivity.this, PostsActivity.class); - i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); - mMenuDrawer.closeMenu(); - startActivityWithDelay(i); } } diff --git a/src/org/wordpress/android/util/WPRestClient.java b/src/org/wordpress/android/util/WPRestClient.java new file mode 100644 index 000000000000..07881da22d36 --- /dev/null +++ b/src/org/wordpress/android/util/WPRestClient.java @@ -0,0 +1,90 @@ +/** + * Wraps the Oauth and RestClient classes and configures them with application specific settings + */ +package org.wordpress.android.util; + +import com.wordpress.rest.Oauth; +import com.wordpress.rest.OauthToken; +import com.wordpress.rest.OauthTokenResponseHandler; +import com.wordpress.rest.RestClient; + +import android.content.SharedPreferences; + +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.RequestParams; + +import java.util.Properties; + +import org.json.JSONObject; + +public class WPRestClient { + + private static final String ACCESS_TOKEN_PREFERNCE="wpcom-access-token"; + private static final String APP_ID_PROPERTY="oauth.app_id"; + private static final String APP_SECRET_PROPERTY="oauth.app_secret"; + private static final String APP_REDIRECT_PROPERTY="oauth.redirect_uri"; + + private Oauth mOauth; + private RestClient mRestClient; + private SharedPreferences mPrefs; + + public WPRestClient(Properties config, SharedPreferences prefs){ + mPrefs = prefs; + // configure Oauth with app credentials + mOauth = new Oauth(config.getProperty(APP_ID_PROPERTY), + config.getProperty(APP_SECRET_PROPERTY), + config.getProperty(APP_REDIRECT_PROPERTY)); + // load an existing access token from prefs if we have one + mRestClient = new RestClient(prefs.getString(ACCESS_TOKEN_PREFERNCE, null)); + } + /** + * Authenticate the user using WordPress.com Oauth + */ + public void requestAccessToken(String username, String password, final OauthTokenResponseHandler handler){ + mOauth.requestAccessToken(username, password, new OauthTokenResponseHandler() { + @Override + public void onStart(){ + handler.onStart(); + } + /** + * Save the token to a preference + */ + @Override + public void onSuccess(OauthToken token){ + mRestClient.setAccessToken(token.toString()); + handler.onSuccess(token); + } + + @Override + public void onFailure(Throwable e, JSONObject response){ + handler.onFailure(e, response); + } + + @Override + public void onFinish(){ + handler.onFinish(); + } + }); + } + /** + * Get notifications + */ + public void getNotifications(AsyncHttpResponseHandler handler){ + RequestParams params = new RequestParams(); + params.put("number", "20"); + get("notifications", params, handler); + } + /** + * Make GET request + */ + public void get(String path, AsyncHttpResponseHandler handler){ + get(path, null, handler); + } + /** + * Make GET request with params + */ + public void get(String path, RequestParams params, AsyncHttpResponseHandler handler){ + mRestClient.get(path, params, handler); + } + +} \ No newline at end of file