summaryrefslogtreecommitdiff
path: root/src/org/fox/ttrss/MainActivity.java
blob: 7b57b3668fdef6aa2088a0fff82782dff5e4e3b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
package org.fox.ttrss;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.jsoup.Jsoup;

import android.animation.LayoutTransition;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
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.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.ViewFlipper;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

public class MainActivity extends Activity {
	private final String TAG = this.getClass().getSimpleName();

	private final static int UPDATE_INITIAL = 1;
	private final static int UPDATE_SEQUENTIAL = 2;
	private final static int UPDATE_OFFLINE = 3;

	private final static int OFFSET_MAX = 100;

	private SharedPreferences m_prefs;
	private String m_themeName = "";
	private boolean m_feedsOpened = false;
	private boolean m_splashDisabled = false;
	protected String m_sessionId;
	protected int m_offset = 0;
	protected int m_limit = 30;
	protected int m_maxId = 0;
	protected int m_updateMode = UPDATE_INITIAL;

	private SQLiteDatabase m_readableDb;
	private SQLiteDatabase m_writableDb;
	
	protected enum SyncStatus { SYNC_INITIAL, SYNC_ONLINE, SYNC_OFFLINE };

	protected MenuItem m_syncStatus;

	protected synchronized SQLiteDatabase getReadableDb() {
		return m_readableDb;
	}
	
	protected synchronized SQLiteDatabase getWritableDb() {
		return m_writableDb;
	}
	
	protected String getSessionId() {
		return m_sessionId;
	}

	protected synchronized void setSessionId(String sessionId) {
		m_sessionId = sessionId;

		SharedPreferences.Editor editor = m_prefs.edit();
		editor.putString("last_session_id", m_sessionId);	
		editor.commit();
	}

	private Timer m_articlesTimer;
	private Timer m_feedsTimer;
	private ArticlesTask m_articlesTask;
	private FeedsTask m_feedsTask;

	private class ArticlesTask extends TimerTask {
		@Override
		public void run() {
			downloadArticles();
		}		
	};

	private class FeedsTask extends TimerTask {
		@Override
		public void run() {
			downloadFeeds();			
		}		
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		m_prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());       

		if (m_prefs.getString("theme", "THEME_DARK").equals("THEME_DARK")) {
			setTheme(R.style.DarkTheme);
		} else {
			setTheme(R.style.LightTheme);
		}

		m_themeName = m_prefs.getString("theme", "THEME_DARK");

		m_sessionId = m_prefs.getString("last_session_id", null);

		if (savedInstanceState != null) {
			m_feedsOpened = savedInstanceState.getBoolean("feedsOpened");
			m_sessionId = savedInstanceState.getString("sessionId");
			m_offset = savedInstanceState.getInt("offset");
			m_limit = savedInstanceState.getInt("limit");
			m_updateMode = savedInstanceState.getInt("updateMode");
			m_maxId = savedInstanceState.getInt("maxId");
			m_splashDisabled = savedInstanceState.getBoolean("splashDisabled");
		}

		// allow database to upgrade before we do anything else
		DatabaseHelper dh = new DatabaseHelper(getApplicationContext());
		m_writableDb = dh.getWritableDatabase();
		m_readableDb = dh.getReadableDatabase();

		if (m_updateMode == UPDATE_INITIAL && !m_splashDisabled) {
			m_writableDb.execSQL("DELETE FROM feeds;");
			//db.execSQL("DELETE FROM articles;");
			
			if (m_maxId == 0) {
				Cursor c = m_readableDb.query("articles", new String[] { BaseColumns._ID } , null, null, null, null, BaseColumns._ID + " DESC LIMIT 1");
				if (c.getCount() == 1) {
					c.moveToFirst();
					//Log.i(TAG, "Last article # " + c.getInt(c.getColumnIndex(BaseColumns._ID)));
					m_maxId = c.getInt(c.getColumnIndex(BaseColumns._ID));
				}
				c.close();
			}
		}

		setContentView(R.layout.main);

		LinearLayout wrapper = (LinearLayout) findViewById(R.id.headlines_wrapper);
		
		LayoutTransition transitioner = new LayoutTransition();
        wrapper.setLayoutTransition(transitioner);

		if (!m_feedsOpened) {
			Log.d(TAG, "Opening feeds fragment...");

			FragmentTransaction ft = getFragmentManager().beginTransaction();			
			FeedsFragment frag = new FeedsFragment();

			ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
			ft.replace(R.id.feeds_container, frag, "FEEDLIST");
			ft.commit();

			m_feedsOpened = true;

		}
		
		if (m_splashDisabled) {
			ViewFlipper vf = (ViewFlipper) findViewById(R.id.main_flipper);
			
			if (vf != null && vf.getDisplayedChild() == 0)
				vf.showNext();
			
			scheduleNextUpdate();
		} else {
			m_feedsTask = new FeedsTask();
			m_feedsTimer = new Timer("UpdateFeeds");
			m_feedsTimer.schedule(m_feedsTask, 1000L, 60*1000L);
		}

		//scheduleNextUpdate();
	}

	@Override
	public void onSaveInstanceState (Bundle out) {
		super.onSaveInstanceState(out);

		out.putBoolean("feedsOpened", m_feedsOpened);
		out.putString("sessionId", m_sessionId);
		out.putInt("offset", m_offset);
		out.putInt("limit", m_limit);
		out.putInt("updateMode", m_updateMode);
		out.putInt("maxId", m_maxId);
		out.putBoolean("splashDisabled", m_splashDisabled);
	}

	@Override
	public void onResume() {
		super.onResume();

		if (!m_prefs.getString("theme", "THEME_DARK").equals(m_themeName)) {
			Intent refresh = new Intent(this, MainActivity.class);
			startActivity(refresh);
			finish();
		}			
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		m_writableDb.close();
		m_readableDb.close();

		if (m_feedsTask != null) m_feedsTask.cancel();
		if (m_articlesTask != null) m_articlesTask.cancel();
		
		if (m_feedsTimer != null)  m_feedsTimer.cancel();
		m_feedsTimer = null;
		
		if (m_articlesTimer != null)  m_articlesTimer.cancel();
		m_articlesTimer = null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);

		m_syncStatus = menu.findItem(R.id.sync_status);

		switch (m_updateMode) {
		case UPDATE_INITIAL:
			setSyncStatus(SyncStatus.SYNC_INITIAL);
			break;
		case UPDATE_SEQUENTIAL:
			setSyncStatus(SyncStatus.SYNC_ONLINE);
			break;
		default:
			setSyncStatus(SyncStatus.SYNC_OFFLINE);
		}		

		return true;
	}

	public void setSyncStatus(SyncStatus status) {
		switch (status) {
		case SYNC_INITIAL:
			m_syncStatus.setTitle(R.string.synchronizing);
			m_syncStatus.setIcon(android.R.drawable.presence_online);
			break;
		case SYNC_ONLINE:
			m_syncStatus.setTitle(R.string.online);
			m_syncStatus.setIcon(android.R.drawable.presence_online);
			break;
		case SYNC_OFFLINE:
			m_syncStatus.setTitle(R.string.offline);
			m_syncStatus.setIcon(android.R.drawable.presence_offline);
			break;
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.preferences:
			Intent intent = new Intent(this, PreferencesActivity.class);
			startActivityForResult(intent, 0);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private synchronized void downloadArticles() {
		ApiRequest api = new ApiRequest(m_sessionId, 
				m_prefs.getString("ttrss_url", null),
				m_prefs.getString("login", null),
				m_prefs.getString("password", null));

		JsonElement result = api.sendRequest(new HashMap<String,String>() {   
			{
				put("sid", m_sessionId);
				put("op", "getHeadlines");
				put("feed_id", "-4");
				put("show_content", "1");
				put("limit", String.valueOf(m_limit));
				put("skip", String.valueOf(m_offset));
				put("view_mode", "unread");

				if (m_offset == 0) {
					put("since_id", String.valueOf(m_maxId));
				}
			}			 
		});

		if (result != null && api.getAuthStatus() == ApiRequest.STATUS_OK) {
			try {
				setSessionId(api.getSessionId());

				int articlesFound = 0;

				try {
					JsonArray feeds_object = (JsonArray) result.getAsJsonArray();

					Type listType = new TypeToken<List<Article>>() {}.getType();
					List<Article> articles = api.m_gson.fromJson(feeds_object, listType);

					/* db.execSQL("DELETE FROM articles"); */

					SQLiteStatement stmtInsert = getWritableDb().compileStatement("INSERT INTO articles " +
							"("+BaseColumns._ID+", unread, marked, published, updated, is_updated, title, link, feed_id, tags, content, excerpt) " +
					"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");

					SQLiteStatement stmtUpdate = getWritableDb().compileStatement("UPDATE articles SET " +
							"unread = ?, marked = ?, published = ?, updated = ?, is_updated = ?, title = ?, link = ?, feed_id = ?, " +
							"tags = ?, content = ?, excerpt = ? WHERE " + BaseColumns._ID + " = ?");

					for (Article article : articles) {
						//Log.d(TAG, "Processing article #" + article.id);

						m_maxId = Math.max(m_maxId, article.id);

						++articlesFound;

						Cursor c = getReadableDb().query("articles", new String[] { BaseColumns._ID } , BaseColumns._ID + "=?", 
								new String[] { String.valueOf(article.id) }, null, null, null);

						String excerpt = Jsoup.parse(article.content).text(); 

						if (excerpt.length() > 250) {
							excerpt = excerpt.substring(0, 250) + "...";
						}

						if (c.getCount() != 0) {
							stmtUpdate.bindLong(1, article.unread ? 1 : 0);
							stmtUpdate.bindLong(2, article.marked ? 1 : 0);
							stmtUpdate.bindLong(3, article.published ? 1 : 0);
							stmtUpdate.bindLong(4, article.updated);
							stmtUpdate.bindLong(5, article.is_updated ? 1 : 0);
							stmtUpdate.bindString(6, article.title);
							stmtUpdate.bindString(7, article.link);
							stmtUpdate.bindLong(8, article.feed_id);
							stmtUpdate.bindString(9, ""); // comma-separated tags
							stmtUpdate.bindString(10, article.content);
							stmtUpdate.bindString(11, excerpt);
							stmtUpdate.bindLong(12, article.id);
							stmtUpdate.execute();

						} else {
							//Log.d(TAG, "article not found");

							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, ""); // comma-separated tags
							stmtInsert.bindString(11, article.content);
							stmtInsert.bindString(12, excerpt);
							stmtInsert.execute();	
						}

						c.close();
					}

					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							FeedsFragment ff = (FeedsFragment) getFragmentManager().findFragmentByTag("FEEDLIST");
							if (ff != null) ff.updateListView();
						}
					});

				} catch (Exception e) {
					e.printStackTrace();
				}

				Log.d(TAG, articlesFound + " articles processed");

				if (articlesFound == m_limit && m_offset < OFFSET_MAX) {

					m_offset += m_limit;

				} else {
					m_offset = 0;

					if (m_updateMode == UPDATE_INITIAL) {
						Log.i(TAG, "Switching to sequential mode...");

						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								setSyncStatus(SyncStatus.SYNC_ONLINE);	
							}
						});
						m_updateMode = UPDATE_SEQUENTIAL;
					}
				}

				m_splashDisabled = true;

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						ViewFlipper vf = (ViewFlipper) findViewById(R.id.main_flipper);
						
						if (vf != null && vf.getDisplayedChild() == 0) {
							vf.showNext();
						}
					}
				});
				
				scheduleNextUpdate();

			} catch (Exception e) {
				e.printStackTrace();
			}										
		} else if (result != null && api.getAuthStatus() != ApiRequest.STATUS_OK) {
			// TODO handle error, e.g auth failed
		} else if (result == null) {
			// TODO could not parse result, server/network error?
		}
	}

	private synchronized void downloadFeeds() {
		ApiRequest api = new ApiRequest(m_sessionId, 
				m_prefs.getString("ttrss_url", null),
				m_prefs.getString("login", null),
				m_prefs.getString("password", null));

		JsonElement result = api.sendRequest(new HashMap<String,String>() {   
			{
				put("sid", m_sessionId);
				put("op", "getFeeds");
				put("cat_id", "-3");
				put("unread_only", "1");
			}			 
		});

		if (result != null && api.getAuthStatus() == ApiRequest.STATUS_OK) {
			try {
				try {
					setSessionId(api.getSessionId());
				} catch (NullPointerException e) {
					//
				}

				JsonArray feeds_object = (JsonArray) result.getAsJsonArray();

				Type listType = new TypeToken<List<Feed>>() {}.getType();
				List<Feed> feeds = api.m_gson.fromJson(feeds_object, listType);

				SQLiteStatement stmtUpdate = getWritableDb().compileStatement("UPDATE feeds SET " +
						"title = ?, feed_url = ?, has_icon = ?, cat_id = ?, last_updated = ? WHERE " +
						BaseColumns._ID + " = ?");

				SQLiteStatement stmtInsert = getWritableDb().compileStatement("INSERT INTO feeds " +
						"("+BaseColumns._ID+", title, feed_url, has_icon, cat_id, last_updated) " +
				"VALUES (?, ?, ?, ?, ?, ?);");

				for (Feed feed : feeds) {
					Cursor c = getReadableDb().query("feeds", new String[] { BaseColumns._ID } , BaseColumns._ID + "=?", 
							new String[] { String.valueOf(feed.id) }, null, null, null);

					if (c.getCount() != 0) {
						stmtUpdate.bindString(1, feed.title);
						stmtUpdate.bindString(2, feed.feed_url);								
						stmtUpdate.bindLong(3, feed.has_icon ? 1 : 0);
						stmtUpdate.bindLong(4, feed.cat_id);
						stmtUpdate.bindLong(5, feed.last_updated);
						stmtUpdate.bindLong(6, feed.id);
						stmtUpdate.execute();								

					} else {
						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.bindLong(6, feed.last_updated);
						stmtInsert.execute();
					}

					c.close();
				} 

				// TODO delete not returned feeds which has no data here

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						/* View pb = findViewById(R.id.loading_progress);
						if (pb != null) pb.setVisibility(View.INVISIBLE); */

						FeedsFragment frag = (FeedsFragment)getFragmentManager().findFragmentByTag("FEEDLIST");
						
						if (frag != null) {						
							frag.updateListView();
						}						
					}
				});
				
				scheduleNextUpdate();

			} catch (Exception e) {
				e.printStackTrace();
			}										
		} else if (result != null && api.getAuthStatus() != ApiRequest.STATUS_OK) {
			// TODO handle error, e.g auth failed
		} else if (result == null) {
			// TODO could not parse result, server/network error?
		}

	}

	protected void scheduleNextUpdate() {

		if (m_articlesTask != null) m_articlesTask.cancel();

		m_articlesTask = new ArticlesTask();

		if (m_updateMode == UPDATE_INITIAL) {
			Log.i(TAG, "Scheduling initial update...");
			m_articlesTimer = new Timer("DownloadInitial");
			m_articlesTimer.schedule(m_articlesTask, 1000L);
		} else {
			Log.i(TAG, "Scheduling sequential update...");
			m_articlesTimer = new Timer("DownloadSequential");
			m_articlesTimer.schedule(m_articlesTask, 60*1000L);
		}
	}				

}