-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathNetworkService.java
291 lines (250 loc) · 10.8 KB
/
NetworkService.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
package com.dimtion.shaarlier.services;
import android.app.IntentService;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.Toast;
import com.dimtion.shaarlier.R;
import com.dimtion.shaarlier.helpers.NetworkManager;
import com.dimtion.shaarlier.helpers.NetworkUtils;
import com.dimtion.shaarlier.utils.Link;
import com.dimtion.shaarlier.utils.ShaarliAccount;
import java.io.IOException;
public class NetworkService extends IntentService {
public static final String EXTRA_MESSENGER="com.dimtion.shaarlier.networkservice.EXTRA_MESSENGER";
public static final int NO_ERROR = 0;
public static final int NETWORK_ERROR = 1;
public static final int TOKEN_ERROR = 2;
public static final int LOGIN_ERROR = 3;
public static final int RETRIEVE_TITLE_ID = 100;
public static final int PREFETCH_LINK = 101;
public static final int INTENT_CHECK = 201;
public static final int INTENT_POST = 202;
public static final int INTENT_PREFETCH = 203;
public static final int INTENT_RETRIEVE_TITLE_AND_DESCRIPTION = 204;
// Notification channels
public static final String CHANNEL_ID = "error_channel";
private String loadedTitle;
private Context mContext;
private Handler mToastHandler;
private Exception mError;
private String loadedDescription;
public NetworkService() {
super("NetworkService");
}
@Override
public void onCreate(){
super.onCreate();
mContext = this;
mToastHandler = new Handler(Looper.getMainLooper());
this.createNotificationChannel();
}
@Override
protected void onHandleIntent(Intent intent) {
int action = intent.getIntExtra("action", -1);
switch (action) {
case INTENT_CHECK:
ShaarliAccount accountToTest = (ShaarliAccount) intent.getSerializableExtra("account");
int shaarliLstatus = checkShaarli(accountToTest);
Exception object = shaarliLstatus == NETWORK_ERROR ? mError : null;
sendBackMessage(intent, shaarliLstatus, object);
break;
case INTENT_POST:
Link link = (Link) intent.getSerializableExtra("link");
if ("".equals(link.getTitle()) && this.loadedTitle != null) {
link.setTitle(this.loadedTitle);
this.loadedTitle = null;
}
if ("".equals(link.getDescription()) && this.loadedDescription != null) {
link.setDescription(this.loadedDescription);
this.loadedDescription = null;
}
postLink(link);
stopSelf();
break;
case INTENT_PREFETCH:
Link sharedLink = (Link) intent.getSerializableExtra("link");
Link prefetchedLink = prefetchLink(sharedLink);
sendBackMessage(intent, PREFETCH_LINK, prefetchedLink);
break;
case INTENT_RETRIEVE_TITLE_AND_DESCRIPTION:
this.loadedTitle = "";
this.loadedDescription = "";
String url = intent.getStringExtra("url");
boolean autoTitle = intent.getBooleanExtra("autoTitle", true);
boolean autoDescription = intent.getBooleanExtra("autoDescription", false);
String[] pageTitleAndDescription = getPageTitleAndDescription(url);
if (autoTitle){
this.loadedTitle = pageTitleAndDescription[0];
}
if (autoDescription){
this.loadedDescription = pageTitleAndDescription[1];
}
sendBackMessage(intent, RETRIEVE_TITLE_ID, pageTitleAndDescription);
break;
default:
// Do nothing
Log.e("NETWORK_ERROR", "Unknown intent action received: " + action);
break;
}
}
private void sendBackMessage(@NonNull Intent intent, int message_id, @Nullable Object message_content) {
// Load the messenger to communicate back to the activity
Messenger messenger = (Messenger) intent.getExtras().get(EXTRA_MESSENGER);
Message msg = Message.obtain();
msg.arg1 = message_id;
msg.obj = message_content;
try {
assert messenger != null;
messenger.send(msg);
} catch (android.os.RemoteException | AssertionError e1) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
/**
* Try to prefetch the data of the link
* Will return exactly the same link if the link does not exist
* or if the prefetch failed.
*
* @param sharedLink partial link
* @return new link with the prefetched data
*/
private Link prefetchLink(Link sharedLink) {
Link prefetchedLink = new Link(sharedLink);
try {
NetworkManager manager = NetworkUtils.getNetworkManager(sharedLink.getAccount());
if (manager.isCompatibleShaarli() && manager.login()) {
prefetchedLink = manager.prefetchLinkData(sharedLink);
} else {
mError = new Exception("Could not connect to shaarli. Possibles causes: unhandled shaarli, bad username or password");
Log.e("ERROR", mError.getMessage());
}
} catch (IOException | NullPointerException e) {
mError = e;
Log.e("ERROR", mError.getMessage());
}
return prefetchedLink;
}
/**
* Check if the given credentials are correct
*
* @param account The account with the credentials
* @return NO_ERROR if nothing is wrong
*/
private int checkShaarli(ShaarliAccount account) {
NetworkManager manager = NetworkUtils.getNetworkManager(account);
try {
if (!manager.isCompatibleShaarli()) {
return TOKEN_ERROR;
}
if (!manager.login()) {
return LOGIN_ERROR;
}
} catch (IOException e) {
mError = e;
return NETWORK_ERROR;
}
return NO_ERROR;
}
private void postLink(Link link) {
boolean posted = true; // Assume it is shared
try {
// Connect the user to the site :
NetworkManager manager = NetworkUtils.getNetworkManager(link.getAccount());
if (manager.isCompatibleShaarli() && manager.login()) {
manager.pushLink(link);
} else {
mError = new Exception("Could not connect to the shaarli. Possibles causes : unhandled shaarli, bad username or password");
posted = false;
}
} catch (IOException | NullPointerException e) {
mError = e;
Log.e("ERROR", e.getMessage());
posted = false;
}
if (!posted) {
sendNotificationShareError(link);
} else {
mToastHandler.post(new DisplayToast(getString(R.string.add_success)));
Log.i("SUCCESS", "Success while sharing link");
}
}
/**
* Display Toast in the main thread
* Thanks: http://stackoverflow.com/a/3955826
*/
private class DisplayToast implements Runnable {
private final String mText;
public DisplayToast(String text) {
mText = text;
}
public void run() {
Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
}
/**
* Retrieve the title of a page
*
* @param url the page to get the title
* @return the title page, "" if there is an error
*/
@NonNull
private String[] getPageTitleAndDescription(String url) {
return NetworkUtils.loadTitleAndDescription(url);
}
private void sendNotificationShareError(Link link) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Failed to share " + link.getTitle())
.setContentText("Press to try again")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_LOW);
// Creates an explicit intent To relaunch this service
Intent resultIntent = new Intent(this, NetworkService.class);
resultIntent.putExtra("action", NetworkService.INTENT_POST);
resultIntent.putExtra("link", link);
resultIntent.putExtra(Intent.EXTRA_TEXT, link.getUrl());
resultIntent.putExtra(Intent.EXTRA_SUBJECT, link.getTitle());
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = PendingIntent.getService(this, 0, resultIntent, 0);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(link.getUrl().hashCode(), mBuilder.build());
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.notification_channel_error_name);
String description = getString(R.string.notification_channel_error_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}