This repository has been archived by the owner on Mar 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathApplication.java
301 lines (257 loc) · 9.65 KB
/
Application.java
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
package com.couchbase.todolite;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.DatabaseOptions;
import com.couchbase.lite.Document;
import com.couchbase.lite.Emitter;
import com.couchbase.lite.Manager;
import com.couchbase.lite.Mapper;
import com.couchbase.lite.View;
import com.couchbase.lite.android.AndroidContext;
import com.couchbase.lite.auth.Authenticator;
import com.couchbase.lite.auth.AuthenticatorFactory;
import com.couchbase.lite.replicator.Replication;
import com.couchbase.lite.util.Log;
import com.couchbase.todolite.util.StringUtil;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Application extends android.app.Application implements Replication.ChangeListener {
public static final String TAG = "ToDoLite";
private static final String SYNC_URL_HTTP = "http://us-east.testfest.couchbasemobile.com:4984/todolite";
// Storage Type: .SQLITE_STORAGE or .FORESTDB_STORAGE
private static final String STORAGE_TYPE = Manager.SQLITE_STORAGE;
// Encryption (Don't store encryption key in the source code. We are doing it here just as an example):
private static final boolean ENCRYPTION_ENABLED = false;
private static final String ENCRYPTION_KEY = "seekrit";
// Logging:
private static final boolean LOGGING_ENABLED = true;
// Guest database:
private static final String GUEST_DATABASE_NAME = "guest";
private Manager mManager;
private Database mDatabase;
private Replication mPull;
private Replication mPush;
private Throwable mReplError;
private String mCurrentUserId;
@Override
public void onCreate() {
super.onCreate();
enableLogging();
}
private void enableLogging() {
if (LOGGING_ENABLED) {
Manager.enableLogging(TAG, Log.VERBOSE);
Manager.enableLogging(Log.TAG, Log.VERBOSE);
Manager.enableLogging(Log.TAG_SYNC_ASYNC_TASK, Log.VERBOSE);
Manager.enableLogging(Log.TAG_SYNC, Log.VERBOSE);
Manager.enableLogging(Log.TAG_QUERY, Log.VERBOSE);
Manager.enableLogging(Log.TAG_VIEW, Log.VERBOSE);
Manager.enableLogging(Log.TAG_DATABASE, Log.VERBOSE);
}
}
private Manager getManager() {
if (mManager == null) {
try {
AndroidContext context = new AndroidContext(getApplicationContext());
mManager = new Manager(context, Manager.DEFAULT_OPTIONS);
} catch (Exception e) {
Log.e(TAG, "Cannot create Manager object", e);
}
}
return mManager;
}
public Database getDatabase() {
return mDatabase;
}
private void setDatabase(Database database) {
this.mDatabase = database;
}
private Database getUserDatabase(String name) {
try {
String dbName = "db" + StringUtil.MD5(name);
DatabaseOptions options = new DatabaseOptions();
options.setCreate(true);
options.setStorageType(STORAGE_TYPE);
options.setEncryptionKey(ENCRYPTION_ENABLED ? ENCRYPTION_KEY : null);
return getManager().openDatabase(dbName, options);
} catch (CouchbaseLiteException e) {
Log.e(TAG, "Cannot create database for name: " + name, e);
}
return null;
}
public void loginAsFacebookUser(Activity activity, String token, String userId, String name) {
setCurrentUserId(userId);
setDatabase(getUserDatabase(userId));
String profileDocID = "p:" + userId;
Document profile = mDatabase.getExistingDocument(profileDocID);
if (profile == null) {
try {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("type", "profile");
properties.put("user_id", userId);
properties.put("name", name);
profile = mDatabase.getDocument(profileDocID);
profile.putProperties(properties);
// Migrate guest data to user:
UserProfile.migrateGuestData(getUserDatabase(GUEST_DATABASE_NAME), profile);
} catch (CouchbaseLiteException e) {
Log.e(TAG, "Cannot create a new user profile", e);
}
}
startReplication(AuthenticatorFactory.createFacebookAuthenticator(token));
login(activity);
}
public void loginAsGuest(Activity activity) {
setDatabase(getUserDatabase(GUEST_DATABASE_NAME));
setCurrentUserId(null);
login(activity);
}
private void login(Activity activity) {
Intent intent = new Intent(activity, ListActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(intent);
activity.finish();
}
public void logout() {
setCurrentUserId(null);
stopReplication();
setDatabase(null);
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setAction(LoginActivity.ACTION_LOGOUT);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
private void setCurrentUserId(String userId) {
this.mCurrentUserId = userId;
}
public String getCurrentUserId() {
return this.mCurrentUserId;
}
/** Replicator */
private URL getSyncUrl() {
URL url = null;
try {
url = new URL(SYNC_URL_HTTP);
} catch (MalformedURLException e) {
Log.e(TAG, "Invalid sync url", e);
}
return url;
}
private void startReplication(Authenticator auth) {
if (mPull == null) {
mPull = mDatabase.createPullReplication(getSyncUrl());
mPull.setContinuous(true);
mPull.setAuthenticator(auth);
mPull.addChangeListener(this);
}
if (mPush == null) {
mPush = mDatabase.createPushReplication(getSyncUrl());
mPush.setContinuous(true);
mPush.setAuthenticator(auth);
mPush.addChangeListener(this);
}
mPull.stop();
mPull.start();
mPush.stop();
mPush.start();
}
private void stopReplication() {
if (mPull != null) {
mPull.removeChangeListener(this);
mPull.stop();
mPull = null;
}
if (mPush != null) {
mPush.removeChangeListener(this);
mPush.stop();
mPush = null;
}
}
@Override
public void changed(Replication.ChangeEvent event) {
Throwable error = null;
if (mPull != null) {
if (error == null)
error = mPull.getLastError();
}
if (error == null || error == mReplError)
error = mPush.getLastError();
if (error != mReplError) {
mReplError = error;
if (mReplError != null)
showErrorMessage(mReplError.getMessage(), null);
}
}
/** Database View */
public View getListsView() {
View view = mDatabase.getView("lists");
if (view.getMap() == null) {
Mapper mapper = new Mapper() {
public void map(Map<String, Object> document, Emitter emitter) {
String type = (String)document.get("type");
if ("list".equals(type))
emitter.emit(document.get("title"), null);
}
};
view.setMap(mapper, "1.0");
}
return view;
}
public View getTasksView() {
View view = mDatabase.getView("tasks");
if (view.getMap() == null) {
Mapper map = new Mapper() {
@Override
public void map(Map<String, Object> document, Emitter emitter) {
if ("task".equals(document.get("type"))) {
List<Object> keys = new ArrayList<Object>();
keys.add(document.get("list_id"));
keys.add(document.get("created_at"));
emitter.emit(keys, document);
}
}
};
view.setMap(map, "1.0");
}
return view;
}
public View getUserProfilesView() {
View view = mDatabase.getView("profiles");
if (view.getMap() == null) {
Mapper map = new Mapper() {
@Override
public void map(Map<String, Object> document, Emitter emitter) {
if ("profile".equals(document.get("type")))
emitter.emit(document.get("name"), null);
}
};
view.setMap(map, "1.0");
}
return view;
}
/** Display error message */
public void showErrorMessage(final String errorMessage, final Throwable throwable) {
runOnUiThread(new Runnable() {
@Override
public void run() {
android.util.Log.e(TAG, errorMessage, throwable);
String msg = String.format("%s: %s",
errorMessage, throwable != null ? throwable : "");
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void runOnUiThread(Runnable runnable) {
Handler mainHandler = new Handler(getApplicationContext().getMainLooper());
mainHandler.post(runnable);
}
}