aboutsummaryrefslogtreecommitdiff
path: root/src/org/fox/ttrss/offline
diff options
context:
space:
mode:
authorAndrew Dolgov <fox@madoka.volgo-balt.ru>2012-06-19 14:18:00 +0400
committerAndrew Dolgov <fox@madoka.volgo-balt.ru>2012-06-19 14:18:00 +0400
commit08397a47af403d64a012a7961e7444254ccaa9a2 (patch)
treeac3f0a2ad3a391fd60f2da3a69211d5f27c3a79b /src/org/fox/ttrss/offline
parent01151df966ed0006246790645b0f3e06c2ca94b8 (diff)
categorize source files
Diffstat (limited to 'src/org/fox/ttrss/offline')
-rw-r--r--src/org/fox/ttrss/offline/OfflineActivity.java1183
-rw-r--r--src/org/fox/ttrss/offline/OfflineArticleFragment.java254
-rw-r--r--src/org/fox/ttrss/offline/OfflineArticlePager.java111
-rw-r--r--src/org/fox/ttrss/offline/OfflineDownloadService.java361
-rw-r--r--src/org/fox/ttrss/offline/OfflineFeedsFragment.java298
-rw-r--r--src/org/fox/ttrss/offline/OfflineHeadlinesFragment.java483
-rw-r--r--src/org/fox/ttrss/offline/OfflineServices.java20
-rw-r--r--src/org/fox/ttrss/offline/OfflineUploadService.java266
8 files changed, 2976 insertions, 0 deletions
diff --git a/src/org/fox/ttrss/offline/OfflineActivity.java b/src/org/fox/ttrss/offline/OfflineActivity.java
new file mode 100644
index 00000000..8849d67e
--- /dev/null
+++ b/src/org/fox/ttrss/offline/OfflineActivity.java
@@ -0,0 +1,1183 @@
+package org.fox.ttrss.offline;
+
+import org.fox.ttrss.DummyFragment;
+import org.fox.ttrss.MainActivity;
+import org.fox.ttrss.OnlineServices;
+import org.fox.ttrss.PreferencesActivity;
+import org.fox.ttrss.R;
+import org.fox.ttrss.OnlineServices.RelativeArticle;
+import org.fox.ttrss.R.anim;
+import org.fox.ttrss.R.id;
+import org.fox.ttrss.R.layout;
+import org.fox.ttrss.R.menu;
+import org.fox.ttrss.R.string;
+import org.fox.ttrss.R.style;
+import org.fox.ttrss.util.DatabaseHelper;
+
+import android.animation.LayoutTransition;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.Fragment;
+import android.app.FragmentTransaction;
+import android.app.NotificationManager;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.content.res.Configuration;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteStatement;
+import android.os.Bundle;
+import android.preference.PreferenceManager;
+import android.provider.BaseColumns;
+import android.util.Log;
+import android.view.ActionMode;
+import android.view.KeyEvent;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.animation.AnimationUtils;
+import android.widget.AdapterView.AdapterContextMenuInfo;
+import android.widget.EditText;
+import android.widget.SearchView;
+import android.widget.TextView;
+import android.widget.Toast;
+
+public class OfflineActivity extends Activity implements
+ OfflineServices {
+ private final String TAG = this.getClass().getSimpleName();
+
+ private SharedPreferences m_prefs;
+ private String m_themeName = "";
+ private Menu m_menu;
+ private boolean m_smallScreenMode;
+ private boolean m_unreadOnly = true;
+ private boolean m_unreadArticlesOnly = true;
+ private boolean m_enableCats = false;
+
+ private int m_activeFeedId = 0;
+ private int m_selectedArticleId = 0;
+
+ private SQLiteDatabase m_readableDb;
+ private SQLiteDatabase m_writableDb;
+
+ @Override
+ public boolean isSmallScreen() {
+ return m_smallScreenMode;
+ }
+
+ private ActionMode m_headlinesActionMode;
+ private HeadlinesActionModeCallback m_headlinesActionModeCallback;
+
+ private class HeadlinesActionModeCallback implements ActionMode.Callback {
+
+ @Override
+ public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
+ return false;
+ }
+
+ @Override
+ public void onDestroyActionMode(ActionMode mode) {
+ deselectAllArticles();
+ m_headlinesActionMode = null;
+ }
+
+ @Override
+ public boolean onCreateActionMode(ActionMode mode, Menu menu) {
+
+ MenuInflater inflater = getMenuInflater();
+ inflater.inflate(R.menu.headlines_action_menu, menu);
+
+ return true;
+ }
+
+ @Override
+ public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
+ onOptionsItemSelected(item);
+ return false;
+ }
+ };
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ initDatabase();
+
+ m_prefs = PreferenceManager
+ .getDefaultSharedPreferences(getApplicationContext());
+
+ if (m_prefs.getString("theme", "THEME_DARK").equals("THEME_DARK")) {
+ setTheme(R.style.DarkTheme);
+ } else {
+ setTheme(R.style.LightTheme);
+ }
+
+ super.onCreate(savedInstanceState);
+
+ NotificationManager nmgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
+ nmgr.cancel(OfflineDownloadService.NOTIFY_DOWNLOADING);
+
+ m_themeName = m_prefs.getString("theme", "THEME_DARK");
+
+ if (savedInstanceState != null) {
+ m_unreadOnly = savedInstanceState.getBoolean("unreadOnly");
+ m_unreadArticlesOnly = savedInstanceState
+ .getBoolean("unreadArticlesOnly");
+ m_activeFeedId = savedInstanceState.getInt("offlineActiveFeedId");
+ m_selectedArticleId = savedInstanceState.getInt("offlineArticleId");
+ }
+
+ m_enableCats = m_prefs.getBoolean("enable_cats", false);
+
+ m_smallScreenMode = (getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) !=
+ Configuration.SCREENLAYOUT_SIZE_XLARGE;
+
+ setContentView(R.layout.main);
+
+ Log.d(TAG, "m_smallScreenMode=" + m_smallScreenMode);
+
+ if (android.os.Build.VERSION.SDK_INT < 14 /* || android.os.Build.VERSION.SDK_INT == 15 */) {
+ if (!m_smallScreenMode) {
+ LayoutTransition transitioner = new LayoutTransition();
+ ((ViewGroup) findViewById(R.id.main)).setLayoutTransition(transitioner);
+ }
+ }
+
+ m_headlinesActionModeCallback = new HeadlinesActionModeCallback();
+
+ initMainMenu();
+
+ findViewById(R.id.loading_container).setVisibility(View.GONE);
+
+ if (m_smallScreenMode) {
+ if (m_selectedArticleId != 0) {
+ findViewById(R.id.feeds_fragment).setVisibility(View.GONE);
+ findViewById(R.id.cats_fragment).setVisibility(View.GONE);
+ findViewById(R.id.headlines_fragment).setVisibility(View.GONE);
+ } else if (m_activeFeedId != 0) {
+ findViewById(R.id.feeds_fragment).setVisibility(View.GONE);
+ findViewById(R.id.article_fragment).setVisibility(View.GONE);
+ findViewById(R.id.cats_fragment).setVisibility(View.GONE);
+ } else {
+ //findViewById(R.id.headlines_fragment).setVisibility(View.GONE);
+ // findViewById(R.id.article_fragment).setVisibility(View.GONE);
+
+ /*
+ * if (m_enableCats && m_activeCategory == null) {
+ * findViewById(R.id.feeds_fragment).setVisibility(View.GONE);
+ * findViewById(R.id.cats_fragment).setVisibility(View.VISIBLE);
+ * } else {
+ * findViewById(R.id.cats_fragment).setVisibility(View.GONE); }
+ */
+
+ findViewById(R.id.cats_fragment).setVisibility(View.GONE);
+ }
+ } else {
+ if (m_selectedArticleId == 0) {
+ findViewById(R.id.article_fragment).setVisibility(View.GONE);
+
+ /*
+ * if (!m_enableCats || m_activeCategory != null)
+ * findViewById(R.id.cats_fragment).setVisibility(View.GONE);
+ * else
+ * findViewById(R.id.feeds_fragment).setVisibility(View.GONE);
+ */
+
+ findViewById(R.id.cats_fragment).setVisibility(View.GONE);
+
+ } else {
+ findViewById(R.id.feeds_fragment).setVisibility(View.GONE);
+ findViewById(R.id.cats_fragment).setVisibility(View.GONE);
+ }
+ }
+
+ if (m_activeFeedId == 0) {
+ FragmentTransaction ft = getFragmentManager()
+ .beginTransaction();
+ OfflineFeedsFragment frag = new OfflineFeedsFragment();
+ ft.replace(R.id.feeds_fragment, frag);
+ ft.commit();
+ }
+ }
+
+ private void initDatabase() {
+ DatabaseHelper dh = new DatabaseHelper(getApplicationContext());
+ m_writableDb = dh.getWritableDatabase();
+ m_readableDb = dh.getReadableDatabase();
+ }
+
+ @Override
+ public synchronized SQLiteDatabase getReadableDb() {
+ return m_readableDb;
+ }
+
+ @Override
+ public synchronized SQLiteDatabase getWritableDb() {
+ return m_writableDb;
+ }
+
+ private void switchOnline() {
+ SharedPreferences localPrefs = getSharedPreferences("localprefs", Context.MODE_PRIVATE);
+ SharedPreferences.Editor editor = localPrefs.edit();
+ editor.putBoolean("offline_mode_active", false);
+ editor.commit();
+
+ Intent refresh = new Intent(this, MainActivity.class);
+ startActivity(refresh);
+ finish();
+ }
+
+ @Override
+ public int getActiveFeedId() {
+ return m_activeFeedId;
+ }
+
+ private void setLoadingStatus(int status, boolean showProgress) {
+ TextView tv = (TextView) findViewById(R.id.loading_message);
+
+ if (tv != null) {
+ tv.setText(status);
+ }
+
+ View pb = findViewById(R.id.loading_progress);
+
+ if (pb != null) {
+ pb.setVisibility(showProgress ? View.VISIBLE : View.GONE);
+ }
+ }
+
+ @Override
+ public void onSaveInstanceState(Bundle out) {
+ super.onSaveInstanceState(out);
+
+ out.putBoolean("unreadOnly", m_unreadOnly);
+ out.putBoolean("unreadArticlesOnly", m_unreadArticlesOnly);
+ out.putInt("offlineActiveFeedId", m_activeFeedId);
+ out.putInt("offlineArticleId", m_selectedArticleId);
+ }
+
+ private void setUnreadOnly(boolean unread) {
+ m_unreadOnly = unread;
+
+ refreshViews();
+
+ /*
+ * if (!m_enableCats || m_activeCategory != null ) refreshFeeds(); else
+ * refreshCategories();
+ */
+ }
+
+ @Override
+ public boolean getUnreadOnly() {
+ return m_unreadOnly;
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+
+ boolean needRefresh = !m_prefs.getString("theme", "THEME_DARK").equals(
+ m_themeName)
+ || m_prefs.getBoolean("enable_cats", false) != m_enableCats;
+
+ if (needRefresh) {
+ Intent refresh = new Intent(this, OfflineActivity.class);
+ startActivity(refresh);
+ finish();
+ }
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ MenuInflater inflater = getMenuInflater();
+ inflater.inflate(R.menu.offline_menu, menu);
+
+ m_menu = menu;
+
+ initMainMenu();
+
+ MenuItem item = menu.findItem(R.id.show_feeds);
+
+ if (getUnreadOnly()) {
+ item.setTitle(R.string.menu_all_feeds);
+ } else {
+ item.setTitle(R.string.menu_unread_feeds);
+ }
+
+ return true;
+ }
+
+ private void setMenuLabel(int id, int labelId) {
+ MenuItem mi = m_menu.findItem(id);
+
+ if (mi != null) {
+ mi.setTitle(labelId);
+ }
+ }
+
+ private void goBack(boolean allowQuit) {
+ if (m_smallScreenMode) {
+ if (m_selectedArticleId != 0) {
+ closeArticle();
+ } else if (m_activeFeedId != 0) {
+ //if (m_compatMode) {
+ findViewById(R.id.main).setAnimation(
+ AnimationUtils.loadAnimation(this,
+ R.anim.slide_right));
+ //}
+
+ /*
+ * if (m_activeFeed != null && m_activeFeed.is_cat) {
+ * findViewById
+ * (R.id.headlines_fragment).setVisibility(View.GONE);
+ * findViewById(R.id.cats_fragment).setVisibility(View.VISIBLE);
+ *
+ * refreshCategories(); } else {
+ */
+ findViewById(R.id.headlines_fragment).setVisibility(View.GONE);
+ findViewById(R.id.feeds_fragment).setVisibility(View.VISIBLE);
+ // }
+ m_activeFeedId = 0;
+
+ OfflineFeedsFragment ff = (OfflineFeedsFragment) getFragmentManager()
+ .findFragmentById(R.id.feeds_fragment);
+
+ if (ff != null) {
+ ff.setSelectedFeedId(0);
+ }
+
+ FragmentTransaction ft = getFragmentManager().beginTransaction();
+ ft.replace(R.id.headlines_fragment, new OfflineHeadlinesFragment());
+ ft.commit();
+
+ refreshViews();
+ initMainMenu();
+
+ } else if (allowQuit) {
+ finish();
+ }
+ } else {
+ if (m_selectedArticleId != 0) {
+ closeArticle();
+ } else if (m_activeFeedId != 0) {
+ findViewById(R.id.headlines_fragment).setVisibility(View.INVISIBLE);
+ m_activeFeedId = 0;
+
+ OfflineFeedsFragment ff = (OfflineFeedsFragment) getFragmentManager()
+ .findFragmentById(R.id.feeds_fragment);
+
+ if (ff != null) {
+ ff.setSelectedFeedId(0);
+ }
+
+ FragmentTransaction ft = getFragmentManager().beginTransaction();
+ ft.replace(R.id.headlines_fragment, new OfflineHeadlinesFragment());
+ ft.commit();
+
+ refreshViews();
+ initMainMenu();
+
+ } else if (allowQuit) {
+ finish();
+ }
+ }
+ }
+
+ @Override
+ public void onBackPressed() {
+ goBack(true);
+ }
+
+ /*
+ * @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if
+ * (keyCode == KeyEvent.KEYCODE_BACK) {
+ *
+ * if (m_smallScreenMode) { if (m_selectedArticleId != 0) { closeArticle();
+ * } else if (m_activeFeedId != 0) { if (m_compatMode) {
+ * findViewById(R.id.main).setAnimation(AnimationUtils.loadAnimation(this,
+ * R.anim.slide_right)); }
+ */
+
+ /*
+ * if (m_activeFeed != null && m_activeFeed.is_cat) {
+ * findViewById(R.id.headlines_fragment).setVisibility(View.GONE);
+ * findViewById(R.id.cats_fragment).setVisibility(View.VISIBLE);
+ *
+ * refreshCategories(); } else {
+ *//*
+ * findViewById(R.id.headlines_fragment).setVisibility(View.GONE);
+ * findViewById(R.id.feeds_fragment).setVisibility(View.VISIBLE); //}
+ * m_activeFeedId = 0; refreshViews(); initMainMenu();
+ *
+ * } else { finish(); } } else { if (m_selectedArticleId != 0) {
+ * closeArticle(); } else { finish(); } }
+ *
+ * return false; } return super.onKeyDown(keyCode, event); }
+ */
+
+ private Cursor getArticleById(int articleId) {
+ Cursor c = getReadableDb().query("articles", null,
+ BaseColumns._ID + "=?",
+ new String[] { String.valueOf(articleId) }, null, null, null);
+
+ c.moveToFirst();
+
+ return c;
+ }
+
+ private Cursor getFeedById(int feedId) {
+ Cursor c = getReadableDb().query("feeds", null,
+ BaseColumns._ID + "=?",
+ new String[] { String.valueOf(feedId) }, null, null, null);
+
+ c.moveToFirst();
+
+ return c;
+ }
+
+ private Intent getShareIntent(Cursor article) {
+ String title = article.getString(article.getColumnIndex("title"));
+ String link = article.getString(article.getColumnIndex("link"));
+
+ Intent intent = new Intent(Intent.ACTION_SEND);
+
+ intent.setType("text/plain");
+ //intent.putExtra(Intent.EXTRA_SUBJECT, title);
+ intent.putExtra(Intent.EXTRA_TEXT, title + " " + link);
+
+ return intent;
+ }
+
+ private void shareArticle(int articleId) {
+
+ Cursor article = getArticleById(articleId);
+
+ if (article != null) {
+ shareArticle(article);
+ article.close();
+ }
+ }
+
+ private void shareArticle(Cursor article) {
+ if (article != null) {
+ Intent intent = getShareIntent(article);
+
+ startActivity(Intent.createChooser(intent,
+ getString(R.id.share_article)));
+ }
+ }
+
+ private void refreshHeadlines() {
+ OfflineHeadlinesFragment ohf = (OfflineHeadlinesFragment) getFragmentManager()
+ .findFragmentById(R.id.headlines_fragment);
+
+ if (ohf != null) {
+ ohf.refresh();
+ }
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ final OfflineHeadlinesFragment ohf = (OfflineHeadlinesFragment) getFragmentManager()
+ .findFragmentById(R.id.headlines_fragment);
+
+ switch (item.getItemId()) {
+ case android.R.id.home:
+ goBack(false);
+ return true;
+ case R.id.preferences:
+ Intent intent = new Intent(this, PreferencesActivity.class);
+ startActivityForResult(intent, 0);
+ return true;
+ case R.id.go_online:
+ switchOnline();
+ return true;
+ case R.id.headlines_select:
+ if (ohf != null) {
+ Dialog dialog = new Dialog(this);
+ AlertDialog.Builder builder = new AlertDialog.Builder(this);
+ builder.setTitle(R.string.headlines_select_dialog);
+
+ builder.setSingleChoiceItems(new String[] {
+ getString(R.string.headlines_select_all),
+ getString(R.string.headlines_select_unread),
+ getString(R.string.headlines_select_none) }, 0,
+ new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialog,
+ int which) {
+ switch (which) {
+ case 0:
+ SQLiteStatement stmtSelectAll = getWritableDb()
+ .compileStatement(
+ "UPDATE articles SET selected = 1 WHERE feed_id = ?");
+ stmtSelectAll.bindLong(1, m_activeFeedId);
+ stmtSelectAll.execute();
+ stmtSelectAll.close();
+ break;
+ case 1:
+ SQLiteStatement stmtSelectUnread = getWritableDb()
+ .compileStatement(
+ "UPDATE articles SET selected = 1 WHERE feed_id = ? AND unread = 1");
+ stmtSelectUnread
+ .bindLong(1, m_activeFeedId);
+ stmtSelectUnread.execute();
+ stmtSelectUnread.close();
+ break;
+ case 2:
+ deselectAllArticles();
+ break;
+ }
+
+ refreshViews();
+ initMainMenu();
+
+ dialog.cancel();
+ }
+ });
+
+ dialog = builder.create();
+ dialog.show();
+ }
+ return true;
+ case R.id.headlines_mark_as_read:
+ if (m_activeFeedId != 0) {
+ SQLiteStatement stmt = getWritableDb().compileStatement(
+ "UPDATE articles SET unread = 0 WHERE feed_id = ?");
+ stmt.bindLong(1, m_activeFeedId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ return true;
+ case R.id.share_article:
+ shareArticle(m_selectedArticleId);
+ return true;
+ case R.id.toggle_marked:
+ if (m_selectedArticleId != 0) {
+ SQLiteStatement stmt = getWritableDb().compileStatement(
+ "UPDATE articles SET marked = NOT marked WHERE "
+ + BaseColumns._ID + " = ?");
+ stmt.bindLong(1, m_selectedArticleId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ return true;
+ case R.id.selection_select_none:
+ deselectAllArticles();
+ return true;
+ case R.id.selection_toggle_unread:
+ if (getSelectedArticleCount() > 0 && m_activeFeedId != 0) {
+ SQLiteStatement stmt = getWritableDb()
+ .compileStatement(
+ "UPDATE articles SET unread = NOT unread WHERE selected = 1 AND feed_id = ?");
+ stmt.bindLong(1, m_activeFeedId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ return true;
+ case R.id.selection_toggle_marked:
+ if (getSelectedArticleCount() > 0 && m_activeFeedId != 0) {
+ SQLiteStatement stmt = getWritableDb()
+ .compileStatement(
+ "UPDATE articles SET marked = NOT marked WHERE selected = 1 AND feed_id = ?");
+ stmt.bindLong(1, m_activeFeedId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ return true;
+ case R.id.selection_toggle_published:
+ if (getSelectedArticleCount() > 0 && m_activeFeedId != 0) {
+ SQLiteStatement stmt = getWritableDb()
+ .compileStatement(
+ "UPDATE articles SET published = NOT published WHERE selected = 1 AND feed_id = ?");
+ stmt.bindLong(1, m_activeFeedId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ return true;
+ case R.id.toggle_published:
+ if (m_selectedArticleId != 0) {
+ SQLiteStatement stmt = getWritableDb().compileStatement(
+ "UPDATE articles SET published = NOT published WHERE "
+ + BaseColumns._ID + " = ?");
+ stmt.bindLong(1, m_selectedArticleId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ return true;
+ case R.id.catchup_above:
+ if (m_selectedArticleId != 0 && m_activeFeedId != 0) {
+ SQLiteStatement stmt = getWritableDb().compileStatement(
+ "UPDATE articles SET unread = 0 WHERE updated >= "
+ + "(SELECT updated FROM articles WHERE "
+ + BaseColumns._ID + " = ?) AND feed_id = ?");
+ stmt.bindLong(1, m_selectedArticleId);
+ stmt.bindLong(2, m_activeFeedId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ return true;
+ case R.id.set_unread:
+ if (m_selectedArticleId != 0) {
+ SQLiteStatement stmt = getWritableDb().compileStatement(
+ "UPDATE articles SET unread = 1 WHERE "
+ + BaseColumns._ID + " = ?");
+ stmt.bindLong(1, m_selectedArticleId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ return true;
+ case R.id.show_feeds:
+ setUnreadOnly(!getUnreadOnly());
+
+ if (getUnreadOnly()) {
+ item.setTitle(R.string.menu_all_feeds);
+ } else {
+ item.setTitle(R.string.menu_unread_feeds);
+ }
+
+ return true;
+ default:
+ Log.d(TAG,
+ "onOptionsItemSelected, unhandled id=" + item.getItemId());
+ return super.onOptionsItemSelected(item);
+ }
+ }
+
+ private void refreshFeeds() {
+ OfflineFeedsFragment frag = (OfflineFeedsFragment) getFragmentManager()
+ .findFragmentById(R.id.feeds_fragment);
+
+ if (frag != null) {
+ frag.refresh();
+ }
+ }
+
+ private void closeArticle() {
+ if (m_smallScreenMode) {
+ findViewById(R.id.main).setAnimation(
+ AnimationUtils.loadAnimation(this, R.anim.slide_right));
+ }
+
+ if (m_smallScreenMode) {
+ findViewById(R.id.article_fragment).setVisibility(View.GONE);
+ findViewById(R.id.headlines_fragment).setVisibility(View.VISIBLE);
+ } else {
+ findViewById(R.id.article_fragment).setVisibility(View.GONE);
+ findViewById(R.id.feeds_fragment).setVisibility(View.VISIBLE);
+
+ }
+
+ // we don't want to lose selected article in headlines so we refresh them before setting selected id to 0
+ refreshViews();
+
+ m_selectedArticleId = 0;
+
+ FragmentTransaction ft = getFragmentManager().beginTransaction();
+ ft.replace(R.id.article_fragment, new DummyFragment());
+ ft.commit();
+
+ initMainMenu();
+ }
+
+ private int getSelectedArticleCount() {
+ Cursor c = getReadableDb().query("articles",
+ new String[] { "COUNT(*)" }, "selected = 1", null, null, null,
+ null);
+ c.moveToFirst();
+ int selected = c.getInt(0);
+ c.close();
+
+ return selected;
+ }
+
+ @Override
+ public void initMainMenu() {
+ if (m_menu != null) {
+ int numSelected = getSelectedArticleCount();
+
+ m_menu.setGroupVisible(R.id.menu_group_feeds, false);
+ m_menu.setGroupVisible(R.id.menu_group_headlines, false);
+ m_menu.setGroupVisible(R.id.menu_group_headlines_selection, false);
+ m_menu.setGroupVisible(R.id.menu_group_article, false);
+
+ if (numSelected != 0) {
+ if (m_headlinesActionMode == null)
+ m_headlinesActionMode = startActionMode(m_headlinesActionModeCallback);
+ } else if (m_selectedArticleId != 0) {
+ m_menu.setGroupVisible(R.id.menu_group_article, true);
+ } else if (m_activeFeedId != 0) {
+ m_menu.setGroupVisible(R.id.menu_group_headlines, true);
+
+ MenuItem search = m_menu.findItem(R.id.search);
+
+ SearchView searchView = (SearchView) search.getActionView();
+ searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
+ private String query = "";
+
+ @Override
+ public boolean onQueryTextSubmit(String query) {
+ OfflineHeadlinesFragment frag = (OfflineHeadlinesFragment) getFragmentManager()
+ .findFragmentById(R.id.headlines_fragment);
+
+ if (frag != null) {
+ frag.setSearchQuery(query);
+ this.query = query;
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean onQueryTextChange(String newText) {
+ if (newText.equals("") && !newText.equals(this.query)) {
+ OfflineHeadlinesFragment frag = (OfflineHeadlinesFragment) getFragmentManager()
+ .findFragmentById(R.id.headlines_fragment);
+
+ if (frag != null) {
+ frag.setSearchQuery(newText);
+ this.query = newText;
+ }
+ }
+
+ return false;
+ }
+ });
+
+ } else {
+ m_menu.setGroupVisible(R.id.menu_group_feeds, true);
+ }
+
+ if (numSelected == 0 && m_headlinesActionMode != null) {
+ m_headlinesActionMode.finish();
+ }
+
+ if (m_activeFeedId != 0) {
+ Cursor feed = getFeedById(m_activeFeedId);
+
+ if (feed != null) {
+ getActionBar().setTitle(feed.getString(feed.getColumnIndex("title")));
+ }
+ } else {
+ getActionBar().setTitle(R.string.app_name);
+ }
+
+ if (!m_smallScreenMode) {
+ getActionBar().setDisplayHomeAsUpEnabled(m_selectedArticleId != 0);
+ } else {
+ getActionBar().setDisplayHomeAsUpEnabled(m_selectedArticleId != 0 || m_activeFeedId != 0);
+ }
+ }
+ }
+
+ @Override
+ public void onPause() {
+ super.onPause();
+
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+
+ m_readableDb.close();
+ m_writableDb.close();
+
+ }
+
+ private void refreshViews() {
+ refreshFeeds();
+ refreshHeadlines();
+ }
+
+ @Override
+ public boolean onContextItemSelected(MenuItem item) {
+ AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
+ .getMenuInfo();
+
+ OfflineHeadlinesFragment hf = (OfflineHeadlinesFragment) getFragmentManager()
+ .findFragmentById(R.id.headlines_fragment);
+ OfflineFeedsFragment ff = (OfflineFeedsFragment) getFragmentManager()
+ .findFragmentById(R.id.feeds_fragment);
+
+ switch (item.getItemId()) {
+ case R.id.article_link_copy:
+ if (m_selectedArticleId != 0) {
+ Cursor article = null;
+
+ if (m_selectedArticleId != 0) {
+ article = getArticleById(m_selectedArticleId);
+ } else if (info != null) {
+ article = hf.getArticleAtPosition(info.position);
+ }
+
+ if (article != null) {
+ if (android.os.Build.VERSION.SDK_INT < 11) {
+ @SuppressWarnings("deprecation")
+ android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
+ clipboard.setText(article.getString(article.getColumnIndex("link")));
+ } else {
+ android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
+ clipboard.setText(article.getString(article.getColumnIndex("link")));
+ }
+
+ article.close();
+
+ Toast toast = Toast.makeText(OfflineActivity.this, R.string.text_copied_to_clipboard, Toast.LENGTH_SHORT);
+ toast.show();
+ }
+ }
+ return true;
+ case R.id.article_link_share:
+ if (m_selectedArticleId != 0) {
+ shareArticle(m_selectedArticleId);
+ }
+ return true;
+
+ case R.id.browse_articles:
+ // TODO cat stuff
+ return true;
+ case R.id.browse_feeds:
+ // TODO cat stuff
+ return true;
+ case R.id.catchup_category:
+ // TODO cat stuff
+ return true;
+ case R.id.catchup_feed:
+ if (ff != null) {
+ int feedId = ff.getFeedIdAtPosition(info.position);
+
+ if (feedId != 0) {
+ SQLiteStatement stmt = getWritableDb().compileStatement(
+ "UPDATE articles SET unread = 0 WHERE feed_id = ?");
+ stmt.bindLong(1, feedId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ }
+ return true;
+ case R.id.selection_toggle_unread:
+ if (getSelectedArticleCount() > 0 && m_activeFeedId != 0) {
+ SQLiteStatement stmt = getWritableDb()
+ .compileStatement(
+ "UPDATE articles SET unread = NOT unread WHERE selected = 1 AND feed_id = ?");
+ stmt.bindLong(1, m_activeFeedId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ } else {
+ int articleId = hf.getArticleIdAtPosition(info.position);
+ if (articleId != 0) {
+ SQLiteStatement stmt = getWritableDb().compileStatement(
+ "UPDATE articles SET unread = NOT unread WHERE "
+ + BaseColumns._ID + " = ?");
+ stmt.bindLong(1, articleId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ }
+ return true;
+ case R.id.selection_toggle_marked:
+ if (getSelectedArticleCount() > 0 && m_activeFeedId != 0) {
+ SQLiteStatement stmt = getWritableDb()
+ .compileStatement(
+ "UPDATE articles SET marked = NOT marked WHERE selected = 1 AND feed_id = ?");
+ stmt.bindLong(1, m_activeFeedId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ } else {
+ int articleId = hf.getArticleIdAtPosition(info.position);
+ if (articleId != 0) {
+ SQLiteStatement stmt = getWritableDb().compileStatement(
+ "UPDATE articles SET marked = NOT marked WHERE "
+ + BaseColumns._ID + " = ?");
+ stmt.bindLong(1, articleId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ }
+ return true;
+ case R.id.selection_toggle_published:
+ if (getSelectedArticleCount() > 0 && m_activeFeedId != 0) {
+ SQLiteStatement stmt = getWritableDb()
+ .compileStatement(
+ "UPDATE articles SET published = NOT published WHERE selected = 1 AND feed_id = ?");
+ stmt.bindLong(1, m_activeFeedId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ } else {
+ int articleId = hf.getArticleIdAtPosition(info.position);
+ if (articleId != 0) {
+ SQLiteStatement stmt = getWritableDb().compileStatement(
+ "UPDATE articles SET published = NOT published WHERE "
+ + BaseColumns._ID + " = ?");
+ stmt.bindLong(1, articleId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ }
+ return true;
+ case R.id.share_article:
+ Cursor article = hf.getArticleAtPosition(info.position);
+
+ if (article != null) {
+ shareArticle(article);
+ }
+ return true;
+ case R.id.catchup_above:
+ int articleId = hf.getArticleIdAtPosition(info.position);
+
+ if (articleId != 0 && m_activeFeedId != 0) {
+ SQLiteStatement stmt = getWritableDb().compileStatement(
+ "UPDATE articles SET unread = 0 WHERE updated >= "
+ + "(SELECT updated FROM articles WHERE "
+ + BaseColumns._ID + " = ?) AND feed_id = ?");
+ stmt.bindLong(1, articleId);
+ stmt.bindLong(2, m_activeFeedId);
+ stmt.execute();
+ stmt.close();
+ refreshViews();
+ }
+ return true;
+ default:
+ Log.d(TAG,
+ "onContextItemSelected, unhandled id=" + item.getItemId());
+ return super.onContextItemSelected(item);
+ }
+ }
+
+ @Override
+ public boolean dispatchKeyEvent(KeyEvent event) {
+ int action = event.getAction();
+ int keyCode = event.getKeyCode();
+ switch (keyCode) {
+ case KeyEvent.KEYCODE_VOLUME_DOWN:
+ if (action == KeyEvent.ACTION_DOWN) {
+
+ OfflineHeadlinesFragment ohf = (OfflineHeadlinesFragment) getFragmentManager()
+ .findFragmentById(R.id.headlines_fragment);
+
+ int nextId = getRelativeArticleId(m_selectedArticleId,
+ m_activeFeedId, RelativeArticle.AFTER);
+
+ if (nextId != 0 && ohf != null) {
+ if (m_prefs.getBoolean("combined_mode", false)) {
+ ohf.setActiveArticleId(nextId);
+
+ SQLiteStatement stmt = getWritableDb()
+ .compileStatement(
+ "UPDATE articles SET unread = 0 "
+ + "WHERE " + BaseColumns._ID
+ + " = ?");
+
+ stmt.bindLong(1, nextId);
+ stmt.execute();
+ stmt.close();
+
+ } else {
+ openArticle(nextId, 0);
+ }
+ }
+ }
+ return true;
+ case KeyEvent.KEYCODE_VOLUME_UP:
+ if (action == KeyEvent.ACTION_UP) {
+
+ OfflineHeadlinesFragment ohf = (OfflineHeadlinesFragment) getFragmentManager()
+ .findFragmentById(R.id.headlines_fragment);
+
+ int prevId = getRelativeArticleId(m_selectedArticleId,
+ m_activeFeedId, RelativeArticle.BEFORE);
+
+ if (prevId != 0 && ohf != null) {
+ if (m_prefs.getBoolean("combined_mode", false)) {
+ ohf.setActiveArticleId(prevId);
+
+ SQLiteStatement stmt = getWritableDb()
+ .compileStatement(
+ "UPDATE articles SET unread = 0 "
+ + "WHERE " + BaseColumns._ID
+ + " = ?");
+
+ stmt.bindLong(1, prevId);
+ stmt.execute();
+ stmt.close();
+
+ } else {
+ openArticle(prevId, 0);
+ }
+ }
+ }
+ return true;
+ default:
+ return super.dispatchKeyEvent(event);
+ }
+ }
+
+ private void deselectAllArticles() {
+ getWritableDb().execSQL("UPDATE articles SET selected = 0 ");
+ }
+
+ @Override
+ public int getRelativeArticleId(int baseId, int feedId,
+ OnlineServices.RelativeArticle mode) {
+
+ Cursor c;
+
+ /*
+ * if (baseId == 0) { c = getReadableDb().query("articles", null,
+ * "feed_id = ?", new String[] { String.valueOf(feedId) }, null, null,
+ * "updated DESC LIMIT 1");
+ *
+ * if (c.moveToFirst()) { baseId = c.getInt(0); }
+ *
+ * c.close();
+ *
+ * return baseId; }
+ */
+
+ if (mode == RelativeArticle.BEFORE) {
+ c = getReadableDb().query(
+ "articles",
+ null,
+ "updated > (SELECT updated FROM articles WHERE "
+ + BaseColumns._ID + " = ?) AND feed_id = ?",
+ new String[] { String.valueOf(baseId),
+ String.valueOf(feedId) }, null, null,
+ "updated LIMIT 1");
+
+ } else {
+ c = getReadableDb().query(
+ "articles",
+ null,
+ "updated < (SELECT updated FROM articles WHERE "
+ + BaseColumns._ID + " = ?) AND feed_id = ?",
+ new String[] { String.valueOf(baseId),
+ String.valueOf(feedId) }, null, null,
+ "updated DESC LIMIT 1");
+ }
+
+ int id = 0;
+
+ if (c.moveToFirst()) {
+ id = c.getInt(0);
+ }
+
+ c.close();
+
+ return id;
+ }
+
+ @Override
+ public void viewFeed(int feedId) {
+ m_activeFeedId = feedId;
+
+ initMainMenu();
+
+ if (m_smallScreenMode) {
+ findViewById(R.id.feeds_fragment).setVisibility(View.GONE);
+ findViewById(R.id.headlines_fragment).setVisibility(View.VISIBLE);
+ } else {
+ findViewById(R.id.headlines_fragment).setVisibility(View.VISIBLE);
+ }
+
+ deselectAllArticles();
+
+ if (m_menu != null) {
+ MenuItem search = m_menu.findItem(R.id.search);
+
+ if (search != null) {
+ SearchView sv = (SearchView) search.getActionView();
+ sv.setQuery("", false);
+ }
+ }
+
+ FragmentTransaction ft = getFragmentManager().beginTransaction();
+ OfflineHeadlinesFragment frag = new OfflineHeadlinesFragment();
+ ft.replace(R.id.headlines_fragment, frag);
+ ft.commit();
+
+ }
+
+ @Override
+ public void openArticle(int articleId, int compatAnimation) {
+ m_selectedArticleId = articleId;
+
+ initMainMenu();
+
+ OfflineHeadlinesFragment hf = (OfflineHeadlinesFragment) getFragmentManager()
+ .findFragmentById(R.id.headlines_fragment);
+
+ if (hf != null) {
+ hf.setActiveArticleId(articleId);
+ }
+
+ SQLiteStatement stmt = getWritableDb().compileStatement(
+ "UPDATE articles SET unread = 0 " + "WHERE " + BaseColumns._ID
+ + " = ?");
+
+ stmt.bindLong(1, articleId);
+ stmt.execute();
+ stmt.close();
+
+ Fragment frag;
+
+ if (m_smallScreenMode) {
+ frag = new OfflineArticlePager(articleId);
+ } else {
+ frag = new OfflineArticleFragment(articleId);
+ }
+
+ FragmentTransaction ft = getFragmentManager().beginTransaction();
+ ft.replace(R.id.article_fragment, frag);
+ ft.commit();
+
+ if (m_smallScreenMode) {
+ if (compatAnimation == 0)
+ findViewById(R.id.main).setAnimation(
+ AnimationUtils.loadAnimation(this, R.anim.slide_left));
+ else
+ findViewById(R.id.main).setAnimation(
+ AnimationUtils.loadAnimation(this, compatAnimation));
+ }
+
+ if (m_smallScreenMode) {
+ findViewById(R.id.headlines_fragment).setVisibility(View.GONE);
+ findViewById(R.id.article_fragment).setVisibility(View.VISIBLE);
+ } else {
+ findViewById(R.id.feeds_fragment).setVisibility(View.GONE);
+ findViewById(R.id.cats_fragment).setVisibility(View.GONE);
+ findViewById(R.id.article_fragment).setVisibility(View.VISIBLE);
+ }
+
+ }
+
+ @Override
+ public int getSelectedArticleId() {
+ return m_selectedArticleId;
+ }
+
+ @Override
+ public void setSelectedArticleId(int articleId) {
+ m_selectedArticleId = articleId;
+ refreshViews();
+ }
+} \ No newline at end of file
diff --git a/src/org/fox/ttrss/offline/OfflineArticleFragment.java b/src/org/fox/ttrss/offline/OfflineArticleFragment.java
new file mode 100644
index 00000000..893a7d28
--- /dev/null
+++ b/src/org/fox/ttrss/offline/OfflineArticleFragment.java
@@ -0,0 +1,254 @@
+package org.fox.ttrss.offline;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import org.fox.ttrss.R;
+import org.fox.ttrss.R.attr;
+import org.fox.ttrss.R.id;
+import org.fox.ttrss.R.layout;
+import org.fox.ttrss.R.menu;
+import org.fox.ttrss.util.ImageCacheService;
+import org.jsoup.Jsoup;
+import org.jsoup.nodes.Document;
+import org.jsoup.nodes.Element;
+import org.jsoup.select.Elements;
+
+import android.app.Activity;
+import android.app.Fragment;
+import android.content.SharedPreferences;
+import android.database.Cursor;
+import android.os.Bundle;
+import android.preference.PreferenceManager;
+import android.provider.BaseColumns;
+import android.text.Html;
+import android.text.method.LinkMovementMethod;
+import android.util.TypedValue;
+import android.view.ContextMenu;
+import android.view.ContextMenu.ContextMenuInfo;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.webkit.WebSettings;
+import android.webkit.WebView;
+import android.widget.TextView;
+
+public class OfflineArticleFragment extends Fragment {
+ @SuppressWarnings("unused")
+ private final String TAG = this.getClass().getSimpleName();
+
+ private SharedPreferences m_prefs;
+ private int m_articleId;
+ private Cursor m_cursor;
+ private OfflineServices m_offlineServices;
+
+ public OfflineArticleFragment() {
+ super();
+ }
+
+ public OfflineArticleFragment(int articleId) {
+ super();
+ m_articleId = articleId;
+ }
+
+ @Override
+ public void onCreateContextMenu(ContextMenu menu, View v,
+ ContextMenuInfo menuInfo) {
+
+ getActivity().getMenuInflater().inflate(R.menu.article_link_context_menu, menu);
+ menu.setHeaderTitle(m_cursor.getString(m_cursor.getColumnIndex("title")));
+
+ super.onCreateContextMenu(menu, v, menuInfo);
+
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+
+ if (savedInstanceState != null) {
+ m_articleId = savedInstanceState.getInt("articleId");
+ }
+
+ View view = inflater.inflate(R.layout.article_fragment, container, false);
+
+
+ // TODO change to interface?
+ Activity activity = getActivity();
+
+ if (activity != null) {
+ int orientation = activity.getWindowManager().getDefaultDisplay().getOrientation();
+
+ if (!m_offlineServices.isSmallScreen()) {
+ if (orientation % 2 == 0) {
+ view.findViewById(R.id.splitter_horizontal).setVisibility(View.GONE);
+ } else {
+ view.findViewById(R.id.splitter_vertical).setVisibility(View.GONE);
+ }
+ } else {
+ view.findViewById(R.id.splitter_vertical).setVisibility(View.GONE);
+ view.findViewById(R.id.splitter_horizontal).setVisibility(View.GONE);
+ }
+ } else {
+ view.findViewById(R.id.splitter_horizontal).setVisibility(View.GONE);
+ }
+
+ m_cursor = m_offlineServices.getReadableDb().query("articles", null, BaseColumns._ID + "=?",
+ new String[] { String.valueOf(m_articleId) }, null, null, null);
+
+ m_cursor.moveToFirst();
+
+ if (m_cursor.isFirst()) {
+
+ TextView title = (TextView)view.findViewById(R.id.title);
+
+ if (title != null) {
+
+ String titleStr;
+
+ if (m_cursor.getString(m_cursor.getColumnIndex("title")).length() > 200)
+ titleStr = m_cursor.getString(m_cursor.getColumnIndex("title")).substring(0, 200) + "...";
+ else
+ titleStr = m_cursor.getString(m_cursor.getColumnIndex("title"));
+
+ title.setMovementMethod(LinkMovementMethod.getInstance());
+ title.setText(Html.fromHtml("<a href=\""+m_cursor.getString(m_cursor.getColumnIndex("link")).trim().replace("\"", "\\\"")+"\">" + titleStr + "</a>"));
+ registerForContextMenu(title);
+ }
+
+ WebView web = (WebView)view.findViewById(R.id.content);
+
+ if (web != null) {
+
+ String content;
+ String cssOverride = "";
+
+ WebSettings ws = web.getSettings();
+ ws.setSupportZoom(true);
+ ws.setBuiltInZoomControls(true);
+
+ TypedValue tv = new TypedValue();
+ getActivity().getTheme().resolveAttribute(R.attr.linkColor, tv, true);
+
+ // prevent flicker in ics
+ if (android.os.Build.VERSION.SDK_INT >= 11) {
+ web.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
+ }
+
+ if (m_prefs.getString("theme", "THEME_DARK").equals("THEME_DARK")) {
+ cssOverride = "body { background : transparent; color : #e0e0e0}";
+ //view.setBackgroundColor(android.R.color.black);
+ web.setBackgroundColor(getResources().getColor(android.R.color.transparent));
+ } else {
+ cssOverride = "";
+ }
+
+ String hexColor = String.format("#%06X", (0xFFFFFF & tv.data));
+ cssOverride += " a:link {color: "+hexColor+";} a:visited { color: "+hexColor+";}";
+
+ String articleContent = m_cursor.getString(m_cursor.getColumnIndex("content"));
+ Document doc = Jsoup.parse(articleContent);
+
+ if (doc != null) {
+ if (m_prefs.getBoolean("offline_image_cache_enabled", false)) {
+
+ Elements images = doc.select("img");
+
+ for (Element img : images) {
+ String url = img.attr("src");
+
+ if (ImageCacheService.isUrlCached(url)) {
+ img.attr("src", "file://" + ImageCacheService.getCacheFileName(url));
+ }
+ }
+ }
+
+ // thanks webview for crashing on <video> tag
+ Elements videos = doc.select("video");
+
+ for (Element video : videos)
+ video.remove();
+
+ articleContent = doc.toString();
+ }
+
+ view.findViewById(R.id.attachments_holder).setVisibility(View.GONE);
+
+ String align = m_prefs.getBoolean("justify_article_text", true) ? "text-align : justified" : "";
+
+ switch (Integer.parseInt(m_prefs.getString("font_size", "0"))) {
+ case 0:
+ cssOverride += "body { "+align+"; font-size : 14px; } ";
+ break;
+ case 1:
+ cssOverride += "body { "+align+"; font-size : 18px; } ";
+ break;
+ case 2:
+ cssOverride += "body { "+align+"; font-size : 21px; } ";
+ break;
+ }
+
+ content =
+ "<html>" +
+ "<head>" +
+ "<meta content=\"text/html; charset=utf-8\" http-equiv=\"content-type\">" +
+ //"<meta name=\"viewport\" content=\"target-densitydpi=device-dpi\" />" +
+ "<style type=\"text/css\">" +
+ cssOverride +
+ "img { max-width : 98%; height : auto; }" +
+ "</style>" +
+ "</head>" +
+ "<body>" + articleContent + "</body></html>";
+
+ try {
+ web.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
+ } catch (RuntimeException e) {
+ e.printStackTrace();
+ }
+
+
+ }
+
+ TextView dv = (TextView)view.findViewById(R.id.date);
+
+ if (dv != null) {
+ Date d = new Date(m_cursor.getInt(m_cursor.getColumnIndex("updated")) * 1000L);
+ SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy, HH:mm");
+ dv.setText(df.format(d));
+ }
+
+ TextView tagv = (TextView)view.findViewById(R.id.tags);
+
+ if (tagv != null) {
+ String tagsStr = m_cursor.getString(m_cursor.getColumnIndex("tags"));
+ tagv.setText(tagsStr);
+ }
+ }
+
+ return view;
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+
+ m_cursor.close();
+ }
+
+ @Override
+ public void onSaveInstanceState (Bundle out) {
+ super.onSaveInstanceState(out);
+
+ out.putInt("articleId", m_articleId);
+ }
+
+ @Override
+ public void onAttach(Activity activity) {
+ super.onAttach(activity);
+
+ m_prefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
+
+ m_offlineServices = (OfflineServices)activity;
+ }
+
+
+}
diff --git a/src/org/fox/ttrss/offline/OfflineArticlePager.java b/src/org/fox/ttrss/offline/OfflineArticlePager.java
new file mode 100644
index 00000000..0e3d87ee
--- /dev/null
+++ b/src/org/fox/ttrss/offline/OfflineArticlePager.java
@@ -0,0 +1,111 @@
+package org.fox.ttrss.offline;
+
+import org.fox.ttrss.R;
+import org.fox.ttrss.R.id;
+import org.fox.ttrss.R.layout;
+import org.fox.ttrss.util.FragmentStatePagerAdapter;
+
+import android.app.Activity;
+import android.app.Fragment;
+import android.app.FragmentManager;
+import android.database.sqlite.SQLiteStatement;
+import android.os.Bundle;
+import android.provider.BaseColumns;
+import android.support.v4.view.ViewPager;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+public class OfflineArticlePager extends Fragment {
+
+ private PagerAdapter m_adapter;
+ private OfflineServices m_offlineServices;
+ private OfflineHeadlinesFragment m_hf;
+ private int m_articleId;
+
+ private class PagerAdapter extends FragmentStatePagerAdapter {
+
+ public PagerAdapter(FragmentManager fm) {
+ super(fm);
+ }
+
+ @Override
+ public Fragment getItem(int position) {
+ int articleId = m_hf.getArticleIdAtPosition(position);
+
+ if (articleId != 0) {
+ return new OfflineArticleFragment(articleId);
+ }
+
+ return null;
+ }
+
+ @Override
+ public int getCount() {
+ return m_hf.getArticleCount();
+ }
+
+ }
+
+ public OfflineArticlePager() {
+ super();
+ }
+
+ public OfflineArticlePager(int articleId) {
+ super();
+
+ m_articleId = articleId;
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.article_pager, container, false);
+
+ m_adapter = new PagerAdapter(getActivity().getFragmentManager());
+
+ ViewPager pager = (ViewPager) view.findViewById(R.id.article_pager);
+
+ int position = m_hf.getArticleIdPosition(m_articleId);
+
+ pager.setAdapter(m_adapter);
+ pager.setCurrentItem(position);
+ pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
+
+ @Override
+ public void onPageScrollStateChanged(int arg0) {
+ }
+
+ @Override
+ public void onPageScrolled(int arg0, float arg1, int arg2) {
+ }
+
+ @Override
+ public void onPageSelected(int position) {
+ int articleId = m_hf.getArticleIdAtPosition(position);
+
+ if (articleId != 0) {
+ m_offlineServices.setSelectedArticleId(articleId);
+
+ SQLiteStatement stmt = m_offlineServices.getWritableDb().compileStatement(
+ "UPDATE articles SET unread = 0 " + "WHERE " + BaseColumns._ID
+ + " = ?");
+
+ stmt.bindLong(1, articleId);
+ stmt.execute();
+ stmt.close();
+ }
+ }
+ });
+
+ return view;
+ }
+
+ @Override
+ public void onAttach(Activity activity) {
+ super.onAttach(activity);
+
+ m_hf = (OfflineHeadlinesFragment) getActivity().getFragmentManager().findFragmentById(R.id.headlines_fragment);
+ m_offlineServices = (OfflineServices)activity;
+ }
+
+}
diff --git a/src/org/fox/ttrss/offline/OfflineDownloadService.java b/src/org/fox/ttrss/offline/OfflineDownloadService.java
new file mode 100644
index 00000000..f9dc0bc1
--- /dev/null
+++ b/src/org/fox/ttrss/offline/OfflineDownloadService.java
@@ -0,0 +1,361 @@
+package org.fox.ttrss.offline;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+
+import org.fox.ttrss.ApiRequest;
+import org.fox.ttrss.MainActivity;
+import org.fox.ttrss.R;
+import org.fox.ttrss.R.drawable;
+import org.fox.ttrss.R.string;
+import org.fox.ttrss.types.Article;
+import org.fox.ttrss.types.Feed;
+import org.fox.ttrss.util.DatabaseHelper;
+import org.fox.ttrss.util.ImageCacheService;
+import org.jsoup.Jsoup;
+import org.jsoup.nodes.Document;
+import org.jsoup.nodes.Element;
+import org.jsoup.select.Elements;
+
+import android.app.ActivityManager;
+import android.app.ActivityManager.RunningServiceInfo;
+import android.app.IntentService;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteStatement;
+import android.os.Bundle;
+import android.os.Environment;
+import android.preference.PreferenceManager;
+import android.provider.BaseColumns;
+import android.util.Log;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.reflect.TypeToken;
+
+public class OfflineDownloadService extends IntentService {
+
+ private final String TAG = this.getClass().getSimpleName();
+
+ public static final int NOTIFY_DOWNLOADING = 1;
+ public static final String INTENT_ACTION_SUCCESS = "org.fox.ttrss.intent.action.DownloadComplete";
+
+ private static final int OFFLINE_SYNC_SEQ = 60;
+ private static final int OFFLINE_SYNC_MAX = 500;
+
+ private SQLiteDatabase m_writableDb;
+ private SQLiteDatabase m_readableDb;
+ private int m_articleOffset = 0;
+ private String m_sessionId;
+ private NotificationManager m_nmgr;
+
+ private boolean m_downloadInProgress = false;
+ private boolean m_downloadImages = false;
+ private int m_syncMax;
+ private SharedPreferences m_prefs;
+
+ public OfflineDownloadService() {
+ super("OfflineDownloadService");
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ m_nmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
+ m_prefs = PreferenceManager
+ .getDefaultSharedPreferences(getApplicationContext());
+
+ m_downloadImages = m_prefs.getBoolean("offline_image_cache_enabled", false);
+ m_syncMax = m_prefs.getInt("offline_sync_max", OFFLINE_SYNC_MAX);
+
+ initDatabase();
+ }
+
+ private void updateNotification(String msg) {
+ Notification notification = new Notification(R.drawable.icon,
+ getString(R.string.notify_downloading_title), System.currentTimeMillis());
+
+ PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
+ new Intent(this, MainActivity.class), 0);
+
+ notification.flags |= Notification.FLAG_ONGOING_EVENT;
+ notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
+
+ notification.setLatestEventInfo(this, getString(R.string.notify_downloading_title), msg, contentIntent);
+
+ m_nmgr.notify(NOTIFY_DOWNLOADING, notification);
+ }
+
+ private void updateNotification(int msgResId) {
+ updateNotification(getString(msgResId));
+ }
+
+ private void downloadFailed() {
+ m_readableDb.close();
+ m_writableDb.close();
+
+ // TODO send notification to activity?
+
+ m_downloadInProgress = false;
+ }
+
+ private boolean isCacheServiceRunning() {
+ ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
+ for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
+ if ("org.fox.ttrss.ImageCacheService".equals(service.service.getClassName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public void downloadComplete() {
+ m_downloadInProgress = false;
+
+ // if cache service is running, it will send a finished intent on its own
+ if (!isCacheServiceRunning()) {
+ m_nmgr.cancel(NOTIFY_DOWNLOADING);
+
+ Intent intent = new Intent();
+ intent.setAction(INTENT_ACTION_SUCCESS);
+ intent.addCategory(Intent.CATEGORY_DEFAULT);
+ sendBroadcast(intent);
+ } else {
+ updateNotification(getString(R.string.notify_downloading_images, 0));
+ }
+
+ m_readableDb.close();
+ m_writableDb.close();
+ }
+
+ private void initDatabase() {
+ DatabaseHelper dh = new DatabaseHelper(getApplicationContext());
+ m_writableDb = dh.getWritableDatabase();
+ m_readableDb = dh.getReadableDatabase();
+ }
+
+ private synchronized SQLiteDatabase getReadableDb() {
+ return m_readableDb;
+ }
+
+ private synchronized SQLiteDatabase getWritableDb() {
+ return m_writableDb;
+ }
+
+ @SuppressWarnings("unchecked")
+ private void downloadArticles() {
+ Log.d(TAG, "offline: downloading articles... offset=" + m_articleOffset);
+
+ updateNotification(getString(R.string.notify_downloading_articles, m_articleOffset));
+
+ OfflineArticlesRequest req = new OfflineArticlesRequest(this);
+
+ @SuppressWarnings("serial")
+ HashMap<String,String> map = new HashMap<String,String>() {
+ {
+ put("op", "getHeadlines");
+ put("sid", m_sessionId);
+ put("feed_id", "-4");
+ put("view_mode", "unread");
+ put("show_content", "true");
+ put("skip", String.valueOf(m_articleOffset));
+ put("limit", String.valueOf(OFFLINE_SYNC_SEQ));
+ }
+ };
+
+ req.execute(map);
+ }
+
+ private void downloadFeeds() {
+
+ updateNotification(R.string.notify_downloading_feeds);
+
+ getWritableDb().execSQL("DELETE FROM feeds;");
+
+ ApiRequest req = new ApiRequest(getApplicationContext()) {
+ @Override
+ protected void onPostExecute(JsonElement content) {
+ if (content != null) {
+
+ try {
+ Type listType = new TypeToken<List<Feed>>() {}.getType();
+ List<Feed> feeds = new Gson().fromJson(content, listType);
+
+ SQLiteStatement stmtInsert = getWritableDb().compileStatement("INSERT INTO feeds " +
+ "("+BaseColumns._ID+", title, feed_url, has_icon, cat_id) " +
+ "VALUES (?, ?, ?, ?, ?);");
+
+ for (Feed feed : feeds) {
+ stmtInsert.bindLong(1, feed.id);
+ stmtInsert.bindString(2, feed.title);
+ stmtInsert.bindString(3, feed.feed_url);
+ stmtInsert.bindLong(4, feed.has_icon ? 1 : 0);
+ stmtInsert.bindLong(5, feed.cat_id);
+
+ stmtInsert.execute();
+ }
+
+ stmtInsert.close();
+
+ Log.d(TAG, "offline: done downloading feeds");
+
+ m_articleOffset = 0;
+
+ getWritableDb().execSQL("DELETE FROM articles;");
+
+ downloadArticles();
+ } catch (Exception e) {
+ e.printStackTrace();
+ updateNotification(R.string.offline_switch_error);
+ downloadFailed();
+ }
+
+ } else {
+ updateNotification(getErrorMessage());
+ downloadFailed();
+ }
+ }
+
+ };
+
+ @SuppressWarnings("serial")
+ HashMap<String,String> map = new HashMap<String,String>() {
+ {
+ put("op", "getFeeds");
+ put("sid", m_sessionId);
+ put("cat_id", "-3");
+ put("unread_only", "true");
+ }
+ };
+
+ req.execute(map);
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+
+ m_nmgr.cancel(NOTIFY_DOWNLOADING);
+
+ //m_readableDb.close();
+ //m_writableDb.close();
+ }
+
+ public class OfflineArticlesRequest extends ApiRequest {
+ public OfflineArticlesRequest(Context context) {
+ super(context);
+ }
+
+ @Override
+ protected void onPostExecute(JsonElement content) {
+ if (content != null) {
+ try {
+ Type listType = new TypeToken<List<Article>>() {}.getType();
+ List<Article> articles = new Gson().fromJson(content, listType);
+
+ SQLiteStatement stmtInsert = getWritableDb().compileStatement("INSERT INTO articles " +
+ "("+BaseColumns._ID+", unread, marked, published, updated, is_updated, title, link, feed_id, tags, content) " +
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
+
+ for (Article article : articles) {
+
+ String tagsString = "";
+
+ for (String t : article.tags) {
+ tagsString += t + ", ";
+ }
+
+ tagsString = tagsString.replaceAll(", $", "");
+
+ stmtInsert.bindLong(1, article.id);
+ stmtInsert.bindLong(2, article.unread ? 1 : 0);
+ stmtInsert.bindLong(3, article.marked ? 1 : 0);
+ stmtInsert.bindLong(4, article.published ? 1 : 0);
+ stmtInsert.bindLong(5, article.updated);
+ stmtInsert.bindLong(6, article.is_updated ? 1 : 0);
+ stmtInsert.bindString(7, article.title);
+ stmtInsert.bindString(8, article.link);
+ stmtInsert.bindLong(9, article.feed_id);
+ stmtInsert.bindString(10, tagsString); // comma-separated tags
+ stmtInsert.bindString(11, article.content);
+
+ if (m_downloadImages) {
+ Document doc = Jsoup.parse(article.content);
+
+ if (doc != null) {
+ Elements images = doc.select("img");
+
+ for (Element img : images) {
+ String url = img.attr("src");
+
+ if (url.indexOf("://") != -1) {
+ if (!ImageCacheService.isUrlCached(url)) {
+ Intent intent = new Intent(OfflineDownloadService.this,
+ ImageCacheService.class);
+
+ intent.putExtra("url", url);
+ startService(intent);
+ }
+ }
+ }
+ }
+ }
+
+ try {
+ stmtInsert.execute();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ stmtInsert.close();
+
+ //m_canGetMoreArticles = articles.size() == 30;
+ m_articleOffset += articles.size();
+
+ Log.d(TAG, "offline: received " + articles.size() + " articles");
+
+ if (articles.size() == OFFLINE_SYNC_SEQ && m_articleOffset < m_syncMax) {
+ downloadArticles();
+ } else {
+ downloadComplete();
+ }
+
+ return;
+
+ } catch (Exception e) {
+ updateNotification(R.string.offline_switch_error);
+ Log.d(TAG, "offline: failed: exception when loading articles");
+ e.printStackTrace();
+ downloadFailed();
+ }
+
+ } else {
+ Log.d(TAG, "offline: failed: " + getErrorMessage());
+ updateNotification(getErrorMessage());
+ downloadFailed();
+ }
+ }
+ }
+
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ m_sessionId = intent.getStringExtra("sessionId");
+
+ if (!m_downloadInProgress) {
+ if (m_downloadImages) ImageCacheService.cleanupCache(false);
+
+ updateNotification(R.string.notify_downloading_init);
+ m_downloadInProgress = true;
+
+ downloadFeeds();
+ }
+ }
+}
diff --git a/src/org/fox/ttrss/offline/OfflineFeedsFragment.java b/src/org/fox/ttrss/offline/OfflineFeedsFragment.java
new file mode 100644
index 00000000..abdfe756
--- /dev/null
+++ b/src/org/fox/ttrss/offline/OfflineFeedsFragment.java
@@ -0,0 +1,298 @@
+package org.fox.ttrss.offline;
+
+import java.io.File;
+
+import org.fox.ttrss.R;
+import org.fox.ttrss.R.drawable;
+import org.fox.ttrss.R.id;
+import org.fox.ttrss.R.layout;
+import org.fox.ttrss.R.menu;
+
+import android.app.Activity;
+import android.app.Fragment;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
+import android.database.Cursor;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.os.Bundle;
+import android.os.Environment;
+import android.preference.PreferenceManager;
+import android.provider.BaseColumns;
+import android.util.Log;
+import android.view.ContextMenu;
+import android.view.ContextMenu.ContextMenuInfo;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.AdapterView.AdapterContextMenuInfo;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.ImageView;
+import android.widget.ListView;
+import android.widget.SimpleCursorAdapter;
+import android.widget.TextView;
+
+public class OfflineFeedsFragment extends Fragment implements OnItemClickListener, OnSharedPreferenceChangeListener {
+ private final String TAG = this.getClass().getSimpleName();
+ private SharedPreferences m_prefs;
+ private FeedListAdapter m_adapter;
+ private static final String ICON_PATH = "/data/org.fox.ttrss/icons/";
+ private int m_selectedFeedId;
+ private boolean m_enableFeedIcons;
+ private Cursor m_cursor;
+ private OfflineServices m_offlineServices;
+
+ @Override
+ public void onCreateContextMenu(ContextMenu menu, View v,
+ ContextMenuInfo menuInfo) {
+
+ getActivity().getMenuInflater().inflate(R.menu.feed_menu, menu);
+
+ AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
+ Cursor cursor = (Cursor)m_adapter.getItem(info.position);
+
+ if (cursor != null)
+ menu.setHeaderTitle(cursor.getString(cursor.getColumnIndex("title")));
+
+ super.onCreateContextMenu(menu, v, menuInfo);
+
+ }
+
+ public Cursor createCursor() {
+ String unreadOnly = m_offlineServices.getUnreadOnly() ? "unread > 0" : null;
+
+ String order = m_prefs.getBoolean("sort_feeds_by_unread", false) ? "unread DESC, title" : "title";
+
+ return m_offlineServices.getReadableDb().query("feeds_unread",
+ null, unreadOnly, null, null, null, order);
+ }
+
+ public void refresh() {
+ if (m_cursor != null && !m_cursor.isClosed()) m_cursor.close();
+
+ m_cursor = createCursor();
+
+ if (m_cursor != null) {
+ m_adapter.changeCursor(m_cursor);
+ m_adapter.notifyDataSetChanged();
+ }
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+
+ if (savedInstanceState != null) {
+ m_selectedFeedId = savedInstanceState.getInt("selectedFeedId");
+ }
+
+ View view = inflater.inflate(R.layout.feeds_fragment, container, false);
+
+ ListView list = (ListView)view.findViewById(R.id.feeds);
+
+ m_cursor = createCursor();
+
+ m_adapter = new FeedListAdapter(getActivity(), R.layout.feeds_row, m_cursor,
+ new String[] { "title", "unread" }, new int[] { R.id.title, R.id.unread_counter }, 0);
+
+ list.setAdapter(m_adapter);
+ list.setOnItemClickListener(this);
+ list.setEmptyView(view.findViewById(R.id.no_feeds));
+ registerForContextMenu(list);
+
+ view.findViewById(R.id.loading_container).setVisibility(View.GONE);
+
+ m_enableFeedIcons = m_prefs.getBoolean("download_feed_icons", false);
+
+ return view;
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+
+ if (m_cursor != null && !m_cursor.isClosed()) m_cursor.close();
+ }
+
+ @Override
+ public void onAttach(Activity activity) {
+ super.onAttach(activity);
+
+ m_offlineServices = (OfflineServices)activity;
+
+ m_prefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
+ m_prefs.registerOnSharedPreferenceChangeListener(this);
+
+ }
+
+ @Override
+ public void onSaveInstanceState (Bundle out) {
+ super.onSaveInstanceState(out);
+
+ out.putInt("selectedFeedId", m_selectedFeedId);
+ }
+
+ @Override
+ public void onItemClick(AdapterView<?> av, View view, int position, long id) {
+ ListView list = (ListView)getActivity().findViewById(R.id.feeds);
+
+ if (list != null) {
+ Cursor cursor = (Cursor) list.getItemAtPosition(position);
+
+ if (cursor != null) {
+ int feedId = (int) cursor.getLong(0);
+ Log.d(TAG, "clicked on feed " + feedId);
+
+ m_offlineServices.viewFeed(feedId);
+
+ m_selectedFeedId = feedId;
+
+ m_adapter.notifyDataSetChanged();
+ }
+ }
+ }
+
+ public void setLoadingStatus(int status, boolean showProgress) {
+ if (getView() != null) {
+ TextView tv = (TextView)getView().findViewById(R.id.loading_message);
+
+ if (tv != null) {
+ tv.setText(status);
+ }
+
+ View pb = getView().findViewById(R.id.loading_progress);
+
+ if (pb != null) {
+ pb.setVisibility(showProgress ? View.VISIBLE : View.GONE);
+ }
+ }
+ }
+
+ private class FeedListAdapter extends SimpleCursorAdapter {
+
+
+ public FeedListAdapter(Context context, int layout, Cursor c,
+ String[] from, int[] to, int flags) {
+ super(context, layout, c, from, to, flags);
+ }
+
+ public static final int VIEW_NORMAL = 0;
+ public static final int VIEW_SELECTED = 1;
+
+ public static final int VIEW_COUNT = VIEW_SELECTED+1;
+
+ @Override
+ public int getViewTypeCount() {
+ return VIEW_COUNT;
+ }
+
+ @Override
+ public int getItemViewType(int position) {
+ Cursor cursor = (Cursor) this.getItem(position);
+
+ if (cursor.getLong(0) == m_selectedFeedId) {
+ return VIEW_SELECTED;
+ } else {
+ return VIEW_NORMAL;
+ }
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ View v = convertView;
+
+ Cursor cursor = (Cursor)getItem(position);
+
+ if (v == null) {
+ int layoutId = R.layout.feeds_row;
+
+ switch (getItemViewType(position)) {
+ case VIEW_SELECTED:
+ layoutId = R.layout.feeds_row_selected;
+ break;
+ }
+
+ LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ v = vi.inflate(layoutId, null);
+
+ }
+
+ TextView tt = (TextView) v.findViewById(R.id.title);
+
+ if (tt != null) {
+ tt.setText(cursor.getString(cursor.getColumnIndex("title")));
+ }
+
+ TextView tu = (TextView) v.findViewById(R.id.unread_counter);
+
+ if (tu != null) {
+ tu.setText(String.valueOf(cursor.getInt(cursor.getColumnIndex("unread"))));
+ tu.setVisibility((cursor.getInt(cursor.getColumnIndex("unread")) > 0) ? View.VISIBLE : View.INVISIBLE);
+ }
+
+ ImageView icon = (ImageView)v.findViewById(R.id.icon);
+
+ if (icon != null) {
+
+ if (m_enableFeedIcons) {
+
+ File storage = Environment.getExternalStorageDirectory();
+
+ File iconFile = new File(storage.getAbsolutePath() + ICON_PATH + cursor.getInt(cursor.getColumnIndex(BaseColumns._ID)) + ".ico");
+ if (iconFile.exists()) {
+ Bitmap bmpOrig = BitmapFactory.decodeFile(iconFile.getAbsolutePath());
+ if (bmpOrig != null) {
+ icon.setImageBitmap(bmpOrig);
+ }
+ } else {
+ icon.setImageResource(cursor.getInt(cursor.getColumnIndex("unread")) > 0 ? R.drawable.ic_rss : R.drawable.ic_rss_bw);
+ }
+
+ } else {
+ icon.setImageResource(cursor.getInt(cursor.getColumnIndex("unread")) > 0 ? R.drawable.ic_rss : R.drawable.ic_rss_bw);
+ }
+
+ }
+
+ return v;
+ }
+ }
+
+ public void sortFeeds() {
+ try {
+ refresh();
+ } catch (NullPointerException e) {
+ // activity is gone?
+ } catch (IllegalStateException e) {
+ // we're probably closing and DB is gone already
+ }
+ }
+
+ @Override
+ public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
+ String key) {
+
+ sortFeeds();
+ m_enableFeedIcons = m_prefs.getBoolean("download_feed_icons", false);
+
+ }
+
+ public int getFeedIdAtPosition(int position) {
+ Cursor c = (Cursor)m_adapter.getItem(position);
+
+ if (c != null) {
+ int feedId = c.getInt(0);
+ c.close();
+ return feedId;
+ }
+
+ return 0;
+ }
+
+ public void setSelectedFeedId(int feedId) {
+ m_selectedFeedId = feedId;
+ refresh();
+ }
+
+}
diff --git a/src/org/fox/ttrss/offline/OfflineHeadlinesFragment.java b/src/org/fox/ttrss/offline/OfflineHeadlinesFragment.java
new file mode 100644
index 00000000..59dc7046
--- /dev/null
+++ b/src/org/fox/ttrss/offline/OfflineHeadlinesFragment.java
@@ -0,0 +1,483 @@
+package org.fox.ttrss.offline;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.TimeZone;
+
+import org.fox.ttrss.R;
+import org.fox.ttrss.R.drawable;
+import org.fox.ttrss.R.id;
+import org.fox.ttrss.R.layout;
+import org.fox.ttrss.R.menu;
+import org.fox.ttrss.R.string;
+import org.jsoup.Jsoup;
+
+import android.app.Activity;
+import android.app.Fragment;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteStatement;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.os.Bundle;
+import android.preference.PreferenceManager;
+import android.provider.BaseColumns;
+import android.text.Html;
+import android.text.Html.ImageGetter;
+import android.text.method.LinkMovementMethod;
+import android.util.Log;
+import android.view.ContextMenu;
+import android.view.ContextMenu.ContextMenuInfo;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.AdapterView.AdapterContextMenuInfo;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.CheckBox;
+import android.widget.ImageView;
+import android.widget.ListView;
+import android.widget.SimpleCursorAdapter;
+import android.widget.TextView;
+
+public class OfflineHeadlinesFragment extends Fragment implements OnItemClickListener {
+ public static enum ArticlesSelection { ALL, NONE, UNREAD };
+
+ private final String TAG = this.getClass().getSimpleName();
+
+ private int m_feedId;
+ private int m_activeArticleId;
+ private boolean m_combinedMode = true;
+ private String m_searchQuery = "";
+
+ private SharedPreferences m_prefs;
+
+ private Cursor m_cursor;
+ private ArticleListAdapter m_adapter;
+
+ private OfflineServices m_offlineServices;
+
+ private ImageGetter m_dummyGetter = new ImageGetter() {
+
+ @Override
+ public Drawable getDrawable(String source) {
+ return new BitmapDrawable();
+ }
+
+ };
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+
+ if (m_cursor != null && !m_cursor.isClosed()) m_cursor.close();
+ }
+
+ public int getSelectedArticleCount() {
+ Cursor c = m_offlineServices.getReadableDb().query("articles",
+ new String[] { "COUNT(*)" }, "selected = 1", null, null, null, null);
+ c.moveToFirst();
+ int selected = c.getInt(0);
+ c.close();
+
+ return selected;
+ }
+
+ @Override
+ public void onCreateContextMenu(ContextMenu menu, View v,
+ ContextMenuInfo menuInfo) {
+
+ getActivity().getMenuInflater().inflate(R.menu.headlines_menu, menu);
+
+ if (getSelectedArticleCount() > 0) {
+ menu.setHeaderTitle(R.string.headline_context_multiple);
+ menu.setGroupVisible(R.id.menu_group_single_article, false);
+ } else {
+ AdapterContextMenuInfo info = (AdapterContextMenuInfo)menuInfo;
+ Cursor c = getArticleAtPosition(info.position);
+ menu.setHeaderTitle(c.getString(c.getColumnIndex("title")));
+ //c.close();
+ menu.setGroupVisible(R.id.menu_group_single_article, true);
+ }
+
+ super.onCreateContextMenu(menu, v, menuInfo);
+
+ }
+
+ public void refresh() {
+ if (m_cursor != null && !m_cursor.isClosed()) m_cursor.close();
+
+ m_cursor = createCursor();
+
+ if (m_cursor != null) {
+ m_adapter.changeCursor(m_cursor);
+ setActiveArticleId(m_offlineServices.getSelectedArticleId());
+ m_adapter.notifyDataSetChanged();
+ }
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+
+ if (savedInstanceState != null) {
+ m_feedId = savedInstanceState.getInt("feedId");
+ m_activeArticleId = savedInstanceState.getInt("activeArticleId");
+ //m_selectedArticles = savedInstanceState.getParcelableArrayList("selectedArticles");
+ m_combinedMode = savedInstanceState.getBoolean("combinedMode");
+ m_searchQuery = (String) savedInstanceState.getCharSequence("searchQuery");
+ }
+
+ View view = inflater.inflate(R.layout.headlines_fragment, container, false);
+
+ m_cursor = createCursor();
+
+ ListView list = (ListView)view.findViewById(R.id.headlines);
+ m_adapter = new ArticleListAdapter(getActivity(), R.layout.headlines_row, m_cursor,
+ new String[] { "title" }, new int[] { R.id.title }, 0);
+
+ list.setAdapter(m_adapter);
+ list.setOnItemClickListener(this);
+ list.setEmptyView(view.findViewById(R.id.no_headlines));
+ registerForContextMenu(list);
+
+ view.findViewById(R.id.loading_progress).setVisibility(View.GONE);
+
+ return view;
+ }
+
+ public Cursor createCursor() {
+ if (m_searchQuery.equals("")) {
+ return m_offlineServices.getReadableDb().query("articles",
+ null, "feed_id = ?", new String[] { String.valueOf(m_feedId) }, null, null, "updated DESC");
+ } else {
+ return m_offlineServices.getReadableDb().query("articles",
+ null, "feed_id = ? AND (title LIKE '%' || ? || '%' OR content LIKE '%' || ? || '%')",
+ new String[] { String.valueOf(m_feedId), m_searchQuery, m_searchQuery }, null, null, "updated DESC");
+ }
+ }
+
+ @Override
+ public void onAttach(Activity activity) {
+ super.onAttach(activity);
+ m_offlineServices = (OfflineServices)activity;
+
+ m_feedId = m_offlineServices.getActiveFeedId();
+ m_prefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
+ m_combinedMode = m_prefs.getBoolean("combined_mode", false);
+ }
+
+ @Override
+ public void onItemClick(AdapterView<?> av, View view, int position, long id) {
+ ListView list = (ListView)av;
+
+ Log.d(TAG, "onItemClick=" + position);
+
+ if (list != null) {
+ Cursor cursor = (Cursor)list.getItemAtPosition(position);
+
+ m_activeArticleId = cursor.getInt(0);
+
+ SQLiteStatement stmtUpdate = m_offlineServices.getWritableDb().compileStatement("UPDATE articles SET unread = 0 " +
+ "WHERE " + BaseColumns._ID + " = ?");
+
+ stmtUpdate.bindLong(1, m_activeArticleId);
+ stmtUpdate.execute();
+ stmtUpdate.close();
+
+ if (!m_combinedMode) {
+ m_offlineServices.openArticle(m_activeArticleId, 0);
+ }
+
+ refresh();
+ }
+ }
+
+ @Override
+ public void onSaveInstanceState (Bundle out) {
+ super.onSaveInstanceState(out);
+
+ out.putInt("feedId", m_feedId);
+ out.putInt("activeArticleId", m_activeArticleId);
+ //out.putParcelableArrayList("selectedArticles", m_selectedArticles);
+ out.putBoolean("combinedMode", m_combinedMode);
+ out.putCharSequence("searchQuery", m_searchQuery);
+ }
+
+ public void setLoadingStatus(int status, boolean showProgress) {
+ if (getView() != null) {
+ TextView tv = (TextView)getView().findViewById(R.id.loading_message);
+
+ if (tv != null) {
+ tv.setText(status);
+ }
+
+ View pb = getView().findViewById(R.id.loading_progress);
+
+ if (pb != null) {
+ pb.setVisibility(showProgress ? View.VISIBLE : View.GONE);
+ }
+ }
+ }
+
+ private class ArticleListAdapter extends SimpleCursorAdapter {
+ public ArticleListAdapter(Context context, int layout, Cursor c,
+ String[] from, int[] to, int flags) {
+ super(context, layout, c, from, to, flags);
+ // TODO Auto-generated constructor stub
+ }
+
+ public static final int VIEW_NORMAL = 0;
+ public static final int VIEW_UNREAD = 1;
+ public static final int VIEW_SELECTED = 2;
+ public static final int VIEW_LOADMORE = 3;
+
+ public static final int VIEW_COUNT = VIEW_LOADMORE+1;
+
+
+ public int getViewTypeCount() {
+ return VIEW_COUNT;
+ }
+
+ @Override
+ public int getItemViewType(int position) {
+ Cursor c = (Cursor) getItem(position);
+
+ //Log.d(TAG, "@gIVT " + position + " " + c.getInt(0) + " vs " + m_activeArticleId);
+
+ if (c.getInt(0) == m_activeArticleId) {
+ return VIEW_SELECTED;
+ } else if (c.getInt(c.getColumnIndex("unread")) == 1) {
+ return VIEW_UNREAD;
+ } else {
+ return VIEW_NORMAL;
+ }
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+
+ View v = convertView;
+
+ Cursor article = (Cursor)getItem(position);
+ final int articleId = article.getInt(0);
+
+ if (v == null) {
+ int layoutId = R.layout.headlines_row;
+
+ switch (getItemViewType(position)) {
+ case VIEW_LOADMORE:
+ layoutId = R.layout.headlines_row_loadmore;
+ break;
+ case VIEW_UNREAD:
+ layoutId = R.layout.headlines_row_unread;
+ break;
+ case VIEW_SELECTED:
+ layoutId = R.layout.headlines_row_selected;
+ break;
+ }
+
+ LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ v = vi.inflate(layoutId, null);
+
+ // http://code.google.com/p/android/issues/detail?id=3414
+ ((ViewGroup)v).setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
+ }
+
+ TextView tt = (TextView)v.findViewById(R.id.title);
+
+ if (tt != null) {
+ if (m_combinedMode) {
+ tt.setMovementMethod(LinkMovementMethod.getInstance());
+ tt.setText(Html.fromHtml("<a href=\""+article.getString(article.getColumnIndex("link")).trim().replace("\"", "\\\"")+"\">" +
+ article.getString(article.getColumnIndex("title")) + "</a>"));
+ } else {
+ tt.setText(Html.fromHtml(article.getString(article.getColumnIndex("title"))));
+ }
+ }
+
+ ImageView marked = (ImageView)v.findViewById(R.id.marked);
+
+ if (marked != null) {
+ marked.setImageResource(article.getInt(article.getColumnIndex("marked")) == 1 ? android.R.drawable.star_on : android.R.drawable.star_off);
+
+ marked.setOnClickListener(new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ SQLiteStatement stmtUpdate = m_offlineServices.getWritableDb().compileStatement("UPDATE articles SET marked = NOT marked " +
+ "WHERE " + BaseColumns._ID + " = ?");
+
+ stmtUpdate.bindLong(1, articleId);
+ stmtUpdate.execute();
+ stmtUpdate.close();
+
+ refresh();
+ }
+ });
+ }
+
+ ImageView published = (ImageView)v.findViewById(R.id.published);
+
+ if (published != null) {
+ published.setImageResource(article.getInt(article.getColumnIndex("published")) == 1 ? R.drawable.ic_rss : R.drawable.ic_rss_bw);
+
+ published.setOnClickListener(new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ SQLiteStatement stmtUpdate = m_offlineServices.getWritableDb().compileStatement("UPDATE articles SET published = NOT published " +
+ "WHERE " + BaseColumns._ID + " = ?");
+
+ stmtUpdate.bindLong(1, articleId);
+ stmtUpdate.execute();
+ stmtUpdate.close();
+
+ refresh();
+ }
+ });
+ }
+
+ TextView te = (TextView)v.findViewById(R.id.excerpt);
+
+ if (te != null) {
+ if (!m_combinedMode) {
+ String excerpt = Jsoup.parse(article.getString(article.getColumnIndex("content"))).text();
+
+ if (excerpt.length() > 100)
+ excerpt = excerpt.substring(0, 100) + "...";
+
+ te.setText(excerpt);
+ } else {
+ te.setVisibility(View.GONE);
+ }
+ }
+
+ ImageView separator = (ImageView)v.findViewById(R.id.headlines_separator);
+
+ if (separator != null && m_offlineServices.isSmallScreen()) {
+ separator.setVisibility(View.GONE);
+ }
+
+ TextView content = (TextView)v.findViewById(R.id.content);
+
+ if (content != null) {
+ if (m_combinedMode) {
+ content.setMovementMethod(LinkMovementMethod.getInstance());
+
+ content.setText(Html.fromHtml(article.getString(article.getColumnIndex("content")), m_dummyGetter, null));
+
+ switch (Integer.parseInt(m_prefs.getString("font_size", "0"))) {
+ case 0:
+ content.setTextSize(15F);
+ break;
+ case 1:
+ content.setTextSize(18F);
+ break;
+ case 2:
+ content.setTextSize(21F);
+ break;
+ }
+ } else {
+ content.setVisibility(View.GONE);
+ }
+ }
+
+ v.findViewById(R.id.attachments_holder).setVisibility(View.GONE);
+
+ TextView dv = (TextView) v.findViewById(R.id.date);
+
+ if (dv != null) {
+ Date d = new Date((long)article.getInt(article.getColumnIndex("updated")) * 1000);
+ DateFormat df = new SimpleDateFormat("MMM dd, HH:mm");
+ df.setTimeZone(TimeZone.getDefault());
+ dv.setText(df.format(d));
+ }
+
+ CheckBox cb = (CheckBox) v.findViewById(R.id.selected);
+
+ if (cb != null) {
+ cb.setChecked(article.getInt(article.getColumnIndex("selected")) == 1);
+ cb.setOnClickListener(new OnClickListener() {
+
+ @Override
+ public void onClick(View view) {
+ CheckBox cb = (CheckBox)view;
+
+ SQLiteStatement stmtUpdate = m_offlineServices.getWritableDb().compileStatement("UPDATE articles SET selected = ? " +
+ "WHERE " + BaseColumns._ID + " = ?");
+
+ stmtUpdate.bindLong(1, cb.isChecked() ? 1 : 0);
+ stmtUpdate.bindLong(2, articleId);
+ stmtUpdate.execute();
+ stmtUpdate.close();
+
+ refresh();
+
+ m_offlineServices.initMainMenu();
+
+ }
+ });
+ }
+
+ return v;
+ }
+ }
+
+ public void notifyUpdated() {
+ m_adapter.notifyDataSetChanged();
+ }
+
+ public void setActiveArticleId(int articleId) {
+ m_activeArticleId = articleId;
+ // m_adapter.notifyDataSetChanged();
+
+ ListView list = (ListView)getView().findViewById(R.id.headlines);
+
+ if (list != null) {
+ list.setSelection(getArticleIdPosition(articleId));
+ }
+ }
+
+ public Cursor getArticleAtPosition(int position) {
+ return (Cursor) m_adapter.getItem(position);
+ }
+
+ public int getArticleIdAtPosition(int position) {
+ /*Cursor c = getArticleAtPosition(position);
+
+ if (c != null) {
+ int id = c.getInt(0);
+ return id;
+ } */
+
+ return (int) m_adapter.getItemId(position);
+ }
+
+ public int getActiveArticleId() {
+ return m_activeArticleId;
+ }
+
+ public int getArticleIdPosition(int articleId) {
+ for (int i = 0; i < m_adapter.getCount(); i++) {
+ if (articleId == m_adapter.getItemId(i))
+ return i;
+ }
+
+ return 0;
+ }
+
+ public int getArticleCount() {
+ return m_adapter.getCount();
+ }
+
+ public void setSearchQuery(String query) {
+ if (!m_searchQuery.equals(query)) {
+ m_searchQuery = query;
+ refresh();
+ }
+ }
+
+}
diff --git a/src/org/fox/ttrss/offline/OfflineServices.java b/src/org/fox/ttrss/offline/OfflineServices.java
new file mode 100644
index 00000000..0ad6bd8c
--- /dev/null
+++ b/src/org/fox/ttrss/offline/OfflineServices.java
@@ -0,0 +1,20 @@
+package org.fox.ttrss.offline;
+
+import org.fox.ttrss.OnlineServices;
+import org.fox.ttrss.OnlineServices.RelativeArticle;
+
+import android.database.sqlite.SQLiteDatabase;
+
+public interface OfflineServices {
+ public int getActiveFeedId();
+ public SQLiteDatabase getReadableDb();
+ public SQLiteDatabase getWritableDb();
+ public int getRelativeArticleId(int baseId, int feedId, OnlineServices.RelativeArticle mode);
+ public void viewFeed(int feedId);
+ public void openArticle(int articleId, int compatAnimation);
+ public boolean getUnreadOnly();
+ public int getSelectedArticleId();
+ public void initMainMenu();
+ public boolean isSmallScreen();
+ public void setSelectedArticleId(int articleId);
+}
diff --git a/src/org/fox/ttrss/offline/OfflineUploadService.java b/src/org/fox/ttrss/offline/OfflineUploadService.java
new file mode 100644
index 00000000..54446669
--- /dev/null
+++ b/src/org/fox/ttrss/offline/OfflineUploadService.java
@@ -0,0 +1,266 @@
+package org.fox.ttrss.offline;
+
+import java.util.HashMap;
+
+import org.fox.ttrss.ApiRequest;
+import org.fox.ttrss.MainActivity;
+import org.fox.ttrss.R;
+import org.fox.ttrss.R.drawable;
+import org.fox.ttrss.R.string;
+import org.fox.ttrss.util.DatabaseHelper;
+
+import com.google.gson.JsonElement;
+
+import android.app.IntentService;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.util.Log;
+
+public class OfflineUploadService extends IntentService {
+ private final String TAG = this.getClass().getSimpleName();
+
+ public static final int NOTIFY_UPLOADING = 2;
+ public static final String INTENT_ACTION_SUCCESS = "org.fox.ttrss.intent.action.UploadComplete";
+
+ private SQLiteDatabase m_writableDb;
+ private SQLiteDatabase m_readableDb;
+ private String m_sessionId;
+ private NotificationManager m_nmgr;
+ private boolean m_uploadInProgress = false;
+
+ public OfflineUploadService() {
+ super("OfflineUploadService");
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ m_nmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
+ initDatabase();
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+
+ m_nmgr.cancel(NOTIFY_UPLOADING);
+ }
+
+ private void updateNotification(String msg) {
+ Notification notification = new Notification(R.drawable.icon,
+ getString(R.string.notify_uploading_title), System.currentTimeMillis());
+
+ PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
+ new Intent(this, MainActivity.class), 0);
+
+ notification.flags |= Notification.FLAG_ONGOING_EVENT;
+ notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
+
+ notification.setLatestEventInfo(this, getString(R.string.notify_uploading_title), msg, contentIntent);
+
+ m_nmgr.notify(NOTIFY_UPLOADING, notification);
+ }
+
+ private void updateNotification(int msgResId) {
+ updateNotification(getString(msgResId));
+ }
+
+ private void initDatabase() {
+ DatabaseHelper dh = new DatabaseHelper(getApplicationContext());
+ m_writableDb = dh.getWritableDatabase();
+ m_readableDb = dh.getReadableDatabase();
+ }
+
+ private synchronized SQLiteDatabase getReadableDb() {
+ return m_readableDb;
+ }
+
+ private synchronized SQLiteDatabase getWritableDb() {
+ return m_writableDb;
+ }
+
+ private void uploadRead() {
+ Log.d(TAG, "syncing modified offline data... (read)");
+
+ final String ids = getModifiedIds(ModifiedCriteria.READ);
+
+ if (ids.length() > 0) {
+ ApiRequest req = new ApiRequest(getApplicationContext()) {
+ @Override
+ protected void onPostExecute(JsonElement result) {
+ if (result != null) {
+ uploadMarked();
+ } else {
+ updateNotification(getErrorMessage());
+ uploadFailed();
+ }
+ }
+ };
+
+ @SuppressWarnings("serial")
+ HashMap<String, String> map = new HashMap<String, String>() {
+ {
+ put("sid", m_sessionId);
+ put("op", "updateArticle");
+ put("article_ids", ids);
+ put("mode", "0");
+ put("field", "2");
+ }
+ };
+
+ req.execute(map);
+ } else {
+ uploadMarked();
+ }
+ }
+
+ private enum ModifiedCriteria {
+ READ, MARKED, PUBLISHED
+ };
+
+ private String getModifiedIds(ModifiedCriteria criteria) {
+
+ String criteriaStr = "";
+
+ switch (criteria) {
+ case READ:
+ criteriaStr = "unread = 0";
+ break;
+ case MARKED:
+ criteriaStr = "marked = 1";
+ break;
+ case PUBLISHED:
+ criteriaStr = "published = 1";
+ break;
+ }
+
+ Cursor c = getReadableDb().query("articles", null,
+ "modified = 1 AND " + criteriaStr, null, null, null, null);
+
+ String tmp = "";
+
+ while (c.moveToNext()) {
+ tmp += c.getInt(0) + ",";
+ }
+
+ tmp = tmp.replaceAll(",$", "");
+
+ c.close();
+
+ return tmp;
+ }
+
+ private void uploadMarked() {
+ Log.d(TAG, "syncing modified offline data... (marked)");
+
+ final String ids = getModifiedIds(ModifiedCriteria.MARKED);
+
+ if (ids.length() > 0) {
+ ApiRequest req = new ApiRequest(getApplicationContext()) {
+ @Override
+ protected void onPostExecute(JsonElement result) {
+ if (result != null) {
+ uploadPublished();
+ } else {
+ updateNotification(getErrorMessage());
+ uploadFailed();
+ }
+ }
+ };
+
+ @SuppressWarnings("serial")
+ HashMap<String, String> map = new HashMap<String, String>() {
+ {
+ put("sid", m_sessionId);
+ put("op", "updateArticle");
+ put("article_ids", ids);
+ put("mode", "0");
+ put("field", "0");
+ }
+ };
+
+ req.execute(map);
+ } else {
+ uploadPublished();
+ }
+ }
+
+ private void uploadFailed() {
+ m_readableDb.close();
+ m_writableDb.close();
+
+ // TODO send notification to activity?
+
+ m_uploadInProgress = false;
+ }
+
+ private void uploadSuccess() {
+ getWritableDb().execSQL("UPDATE articles SET modified = 0");
+
+ Intent intent = new Intent();
+ intent.setAction(INTENT_ACTION_SUCCESS);
+ intent.addCategory(Intent.CATEGORY_DEFAULT);
+ sendBroadcast(intent);
+
+ m_readableDb.close();
+ m_writableDb.close();
+
+ m_uploadInProgress = false;
+
+ m_nmgr.cancel(NOTIFY_UPLOADING);
+ }
+
+ private void uploadPublished() {
+ Log.d(TAG, "syncing modified offline data... (published)");
+
+ final String ids = getModifiedIds(ModifiedCriteria.MARKED);
+
+ if (ids.length() > 0) {
+ ApiRequest req = new ApiRequest(getApplicationContext()) {
+ @Override
+ protected void onPostExecute(JsonElement result) {
+ if (result != null) {
+ uploadSuccess();
+ } else {
+ updateNotification(getErrorMessage());
+ uploadFailed();
+ }
+ }
+ };
+
+ @SuppressWarnings("serial")
+ HashMap<String, String> map = new HashMap<String, String>() {
+ {
+ put("sid", m_sessionId);
+ put("op", "updateArticle");
+ put("article_ids", ids);
+ put("mode", "0");
+ put("field", "1");
+ }
+ };
+
+ req.execute(map);
+ } else {
+ uploadSuccess();
+ }
+ }
+
+
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ m_sessionId = intent.getStringExtra("sessionId");
+
+ if (!m_uploadInProgress) {
+ m_uploadInProgress = true;
+
+ updateNotification(R.string.notify_uploading_sending_data);
+
+ uploadRead();
+ }
+ }
+
+}