summaryrefslogtreecommitdiff
path: root/orgfoxttrss/src/main/java/org/fox/ttrss/offline/OfflineUploadService.java
blob: 4c3349d4510ddddf42736e735e693f3f9f1b2ee5 (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
package org.fox.ttrss.offline;

import java.util.HashMap;

import org.fox.ttrss.ApiRequest;
import org.fox.ttrss.OnlineActivity;
import org.fox.ttrss.R;
import org.fox.ttrss.util.DatabaseHelper;

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.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.google.gson.JsonElement;

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;
	private boolean m_batchMode = 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);
	}

	@SuppressWarnings("deprecation")
	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, OnlineActivity.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", "1");
					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");

		if (m_batchMode) {
			
			SharedPreferences localPrefs = getSharedPreferences("localprefs", Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = localPrefs.edit();
			editor.putBoolean("offline_mode_active", false);
			editor.commit();
			
		} else {
	        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", "1");
					put("field", "1");
				}
			};

			req.execute(map);
		} else {
			uploadSuccess();
		}
	}

	
	@Override
	protected void onHandleIntent(Intent intent) {
		try {
			if (getWritableDb().isDbLockedByCurrentThread() || getWritableDb().isDbLockedByOtherThreads()) {
				return;
			}
	
			m_sessionId = intent.getStringExtra("sessionId");
			m_batchMode = intent.getBooleanExtra("batchMode", false);
	
			if (!m_uploadInProgress) {
				m_uploadInProgress = true;
	
				updateNotification(R.string.notify_uploading_sending_data);
				
				uploadRead();			
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}