-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathSubscriptionWork.java
More file actions
282 lines (218 loc) · 10.5 KB
/
Copy pathSubscriptionWork.java
File metadata and controls
282 lines (218 loc) · 10.5 KB
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
package cn.gov.xivpn2.service;
import static android.content.Context.MODE_PRIVATE;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.util.Base64;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
import androidx.work.ForegroundInfo;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import javax.net.ssl.X509TrustManager;
import cn.gov.xivpn2.BuildConfig;
import cn.gov.xivpn2.NotificationID;
import cn.gov.xivpn2.R;
import cn.gov.xivpn2.Utils;
import cn.gov.xivpn2.database.AppDatabase;
import cn.gov.xivpn2.database.Proxy;
import cn.gov.xivpn2.database.Rules;
import cn.gov.xivpn2.database.Subscription;
import cn.gov.xivpn2.service.sharelink.BadShareLinkException;
import cn.gov.xivpn2.service.sharelink.MarshalProxyException;
import cn.gov.xivpn2.service.sharelink.ShareLinkRegistry;
import cn.gov.xivpn2.ui.CrashLogActivity;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class SubscriptionWork extends Worker {
private static final String TAG = "SubscriptionWorker";
public SubscriptionWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
Log.i(TAG, "doWork");
// start foreground service
Notification foregroundNotification = new Notification.Builder(getApplicationContext(), "XiVPNSubscriptions")
.setContentText(getApplicationContext().getString(R.string.subscription_updating))
.setOngoing(true)
.setSmallIcon(R.drawable.baseline_refresh_24)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
setForegroundAsync(new ForegroundInfo(NotificationID.getID(), foregroundNotification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE));
} else {
setForegroundAsync(new ForegroundInfo(NotificationID.getID(), foregroundNotification));
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e(TAG, "sleep", e);
return Result.success();
}
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("subscription_no_verify", false)) {
Log.w(TAG, "subscription no verify");
builder.sslSocketFactory(Utils.trustAllSslSocketFactory, ((X509TrustManager) Utils.trustAllCerts[0]));
builder.hostnameVerifier((hostname, session) -> true);
}
OkHttpClient client = builder.build();
for (Subscription subscription : AppDatabase.getInstance().subscriptionDao().findAll()) {
// update subscription
Log.i(TAG, "begin update: " + subscription.label + ", " + subscription.url);
Response response = null;
String body = null;
int statusCode = -1;
try {
Request request = new Request.Builder()
.url(subscription.url)
.header("User-Agent", "XiVPN/" + BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")")
.build();
response = client.newCall(request).execute();
// delete old proxies
AppDatabase.getInstance().proxyDao().deleteBySubscription(subscription.label);
// parse subscription and add proxies
statusCode = response.code();
body = response.body().string();
if ("v2rayng".equals(subscription.type)) {
parseV2rayng(body, subscription.label);
} else if ("xray-json".equals(subscription.type)) {
parseXrayJson(body, subscription.label);
} else {
throw new IllegalArgumentException("unknown subscription type: " + subscription.type);
}
Notification notification = new Notification.Builder(getApplicationContext(), "XiVPNSubscriptions")
.setContentTitle(getApplicationContext().getString(R.string.subscription_updated) + subscription.label)
.setSmallIcon(R.drawable.outline_info_24)
.build();
getApplicationContext().getSystemService(NotificationManager.class).notify(NotificationID.getID(), notification);
} catch (Exception e) {
Log.e(TAG, "update " + subscription.label, e);
// save error message to a file
String fileName = "subscription_" + UUID.randomUUID() + ".txt";
File file = new File(getApplicationContext().getCacheDir(), fileName);
try {
StringBuilder sb = new StringBuilder();
sb.append("Could not update subscription: ").append(subscription.label).append("\n\n");
sb.append(e.getClass().getSimpleName()).append(": ").append(e.getMessage()).append("\n\n");
if (statusCode > 0) {
sb.append("Response status code: ").append(statusCode).append("\n\n");
if (body != null) {
sb.append("Response Body:\n").append(body).append("\n\n");
}
}
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(sb.toString().getBytes(StandardCharsets.UTF_8));
outputStream.close();
} catch (IOException e2) {
Log.e(TAG, "write crash log", e2);
}
Intent intent = new Intent(getApplicationContext(), CrashLogActivity.class);
intent.putExtra("FILE", fileName);
// post error message
Notification notification = new Notification.Builder(getApplicationContext(), "XiVPNSubscriptions")
.setContentTitle(getApplicationContext().getString(R.string.subscription_error) + subscription.label)
.setContentText(getApplicationContext().getString(R.string.click_for_details))
.setSmallIcon(R.drawable.baseline_error_24)
.setContentIntent(PendingIntent.getActivity(getApplicationContext(), NotificationID.getID(), intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE))
.build();
getApplicationContext().getSystemService(NotificationManager.class).notify(NotificationID.getID(), notification);
} finally {
if (response != null) {
try {
response.close();
} catch (Exception e) {
Log.e(TAG, "close response", e);
}
}
}
}
try {
Rules.resetDeletedProxies(getApplicationContext().getSharedPreferences("XIVPN", MODE_PRIVATE), getApplicationContext().getFilesDir());
} catch (IOException e) {
Log.e(TAG, "reset deleted proxies", e);
}
XiVPNService.markConfigStale(getApplicationContext());
Log.i(TAG, "doWork finish");
return Result.success();
}
/**
* Import proxies from xray json subscription
*/
public void parseXrayJson(String text, String subscription) {
Gson gson = new Gson();
JsonArray jsonArray = gson.fromJson(text, JsonArray.class);
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
String remarks = "";
if (jsonObject.has("remarks") && !jsonObject.get("remarks").isJsonNull() && jsonObject.get("remarks").isJsonPrimitive()) {
remarks = jsonObject.get("remarks").getAsString();
}
if (remarks == null || remarks.isBlank()) remarks = "Configuration " + i;
jsonObject.remove("remarks");
Proxy proxy = new Proxy();
proxy.protocol = "xray-json";
proxy.subscription = subscription;
proxy.config = gson.toJson(jsonObject);
proxy.label = remarks;
String baseLabel = proxy.label;
int n = 2;
while (AppDatabase.getInstance().proxyDao().find(proxy.label, proxy.subscription) != null) {
// add number to label if already exists
proxy.label = baseLabel + " " + n;
n++;
}
AppDatabase.getInstance().proxyDao().add(proxy);
}
}
/**
* Parse subscription text and add proxies
*
* @param text base64 encoded, one line per proxy
*/
public static void parseV2rayng(String text, String label) {
// decode base64
String textDecoded = new String(Base64.decode(text, Base64.DEFAULT), StandardCharsets.UTF_8);
String[] lines = textDecoded.split("\\r?\\n");
for (String line : lines) {
line = line.replace(" ", "%20").replace("|", "%7c");
Log.i(TAG, "parse " + line);
try {
parseLine(line, label);
} catch (Exception e) {
Log.e(TAG, "line: " + line);
Log.e(TAG, "parse line", e);
}
}
}
public static void parseLine(String line, String subscription) throws BadShareLinkException {
Proxy proxy = ShareLinkRegistry.parse(line);
if (proxy == null) return;
proxy.subscription = subscription;
int n = 2;
String baseLabel = proxy.label;
while (AppDatabase.getInstance().proxyDao().find(proxy.label, proxy.subscription) != null) {
// add number to label if already exists
proxy.label = baseLabel + " " + n;
n++;
}
AppDatabase.getInstance().proxyDao().add(proxy);
}
public static String marshalProxy(Proxy proxy) throws MarshalProxyException {
return ShareLinkRegistry.marshal(proxy);
}
}