-
Notifications
You must be signed in to change notification settings - Fork 56
/
TinkerClientAPI.java
522 lines (462 loc) · 19 KB
/
TinkerClientAPI.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
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
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Shengjie Sim Sun
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.tencent.tinker.server.client;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import com.tencent.tinker.lib.util.TinkerLog;
import com.tencent.tinker.server.model.DataFetcher;
import com.tencent.tinker.server.model.TinkerClientUrl;
import com.tencent.tinker.server.model.request.FailReport;
import com.tencent.tinker.server.model.request.SuccessReport;
import com.tencent.tinker.server.model.response.SyncResponse;
import com.tencent.tinker.server.urlconnection.UrlConnectionUrlLoader;
import com.tencent.tinker.server.utils.Conditions;
import com.tencent.tinker.server.utils.Preconditions;
import com.tencent.tinker.server.utils.ServerUtils;
import com.tencent.tinker.server.utils.VersionUtils;
import java.io.File;
import java.io.InputStream;
public class TinkerClientAPI {
public static final String TAG = "Tinker.ClientImpl";
private static final String REPORT_APPLY_SUCCESS_URL = "http://stat.tinkerpatch.com/succApply.php";
private static final String REPORT_DOWNLOAD_SUCCESS_URL = "http://stat.tinkerpatch.com/succ.php";
private static final String REPORT_FAIL_URL = "http://stat.tinkerpatch.com/err.php";
private static volatile TinkerClientAPI clientAPI;
final Conditions conditions;
final VersionUtils versionUtils;
private final String appVersion;
private final String appKey;
private final String host;
private final boolean debug;
private final UrlConnectionUrlLoader loader;
TinkerClientAPI(
String appKey, String appVersion, String host,
Boolean debug, Conditions conditions, UrlConnectionUrlLoader loader, VersionUtils versionUtils) {
this.appVersion = appVersion;
this.appKey = appKey;
this.host = host;
this.debug = debug;
this.conditions = conditions;
this.loader = loader;
this.versionUtils = versionUtils;
}
/**
* Singleton get method for Tinker clientAPI, you need invoke
* {@link #init(Context, String, String, Boolean)} before it invoke.
*
* @return the instance of {@link TinkerClientAPI}
*/
public static TinkerClientAPI get() {
if (clientAPI == null) {
throw new RuntimeException("Please invoke init Tinker Client first");
}
return clientAPI;
}
/**
* init the Tinker Client, it only effect at first time.
* you should only invoke once in your app lifecycle
*
* @param context {@link Context} context
* @param appKey your appKey get from <a href=tinkerpatch.com>tinkerpatch.com<a/>
* @param appVersion your app version, this is "App版本号" in tinkerpatch.com
* @param debug use debug config, which is "开发预览" in tinkerpatch.com
* @return {@link #TinkerClientAPI} tinker patch clientAPI
*/
public static TinkerClientAPI init(Context context, String appKey, String appVersion, Boolean debug) {
if (clientAPI == null) {
synchronized (TinkerClientAPI.class) {
if (clientAPI == null) {
clientAPI = new Builder()
.appKey(appKey)
.appVersion(appVersion)
.debug(debug)
.conditions(context)
.versionUtils(new VersionUtils(context, appVersion))
.build();
}
}
}
return clientAPI;
}
public Conditions params(String key, String value) {
return this.conditions.set(key, value);
}
public void updateTinkerVersion(Integer newVersion, String md5) {
versionUtils.updateVersionProperty(
getAppVersion(), newVersion, md5, versionUtils.grayValue(), versionUtils.id()
);
}
public void update(final Context context, final PatchRequestCallback callback) {
if (callback == null) {
throw new RuntimeException("callback can't be null");
}
if (!callback.beforePatchRequest()) {
return;
}
sync(new DataFetcher.DataCallback<String>() {
@Override
public void onDataReady(String data) {
final SyncResponse response = SyncResponse.fromJson(data);
if (response == null) {
callback.onPatchSyncFail(new RuntimeException("Can't sync with version: response == null"));
} else {
TinkerLog.d(TAG, "sync response in update:" + response);
if (response.isRollback) {
callback.onPatchRollback();
return;
}
if (response.isPaused) {
TinkerLog.d(TAG, "Needn't update, sync response is: " + response.toString()
+ "\ngray: " + versionUtils.grayValue());
return;
}
if (!TextUtils.isEmpty(response.conditions)) {
callback.updatePatchConditions();
}
final Integer newVersion = Integer.parseInt(response.version);
if (versionUtils.isUpdate(newVersion, getAppVersion())
&& versionUtils.isInGrayGroup(response.grayValue)
&& conditions.check(response.conditions)) {
DataFetcher.DataCallback<File> downloadCallback = new DataFetcher.DataCallback<File>() {
@Override
public void onDataReady(File data) {
callback.onPatchUpgrade(data, newVersion, getCurrentPatchVersion());
}
@Override
public void onLoadFailed(Exception e) {
callback.onPatchDownloadFail(e, newVersion, getCurrentPatchVersion());
}
};
String patchPath = ServerUtils.getServerFile(
context, getAppVersion(), response.version
).getAbsolutePath();
download(response.version, patchPath, downloadCallback);
} else {
TinkerLog.d(TAG, "Needn't update, sync response is: " + response.toString()
+ "\ngray: " + versionUtils.grayValue());
}
}
}
@Override
public void onLoadFailed(Exception e) {
callback.onPatchSyncFail(e);
}
});
}
/**
* sync http://{Host}/{appKey}/{appVersion}?d={deviceId}&v={timestamp}
*
* @param callback the request callback
*/
public void sync(final DataFetcher.DataCallback<String> callback) {
Uri.Builder urlBuilder = Uri.parse(this.host).buildUpon();
if (clientAPI.debug) {
urlBuilder.appendPath("dev");
}
final String url = urlBuilder.appendPath(this.appKey)
.appendPath(this.appVersion)
.appendQueryParameter("d", versionUtils.id())
.appendQueryParameter("v", String.valueOf(System.currentTimeMillis()))
.build().toString();
TinkerClientUrl tkClientUrl = new TinkerClientUrl.Builder().url(url).build();
final DataFetcher<InputStream> dataFetcher = loader.buildLoadData(tkClientUrl);
dataFetcher.loadData(new DataFetcher.DataCallback<InputStream>() {
@Override
public void onDataReady(InputStream data) {
if (callback == null) {
return;
}
try {
String response = ServerUtils.readStreamToString(data, ServerUtils.CHARSET);
TinkerLog.d(TAG, "tinker server sync respond:" + response);
SyncResponse.fromJson(response);
callback.onDataReady(response);
} catch (Exception e) {
callback.onLoadFailed(e);
} finally {
dataFetcher.cleanup();
}
}
@Override
public void onLoadFailed(Exception e) {
if (callback == null) {
return;
}
try {
callback.onLoadFailed(e);
} finally {
dataFetcher.cleanup();
}
}
});
}
/**
* download
* http://{Host}/{appKey}/{appVersion}/file{patchVersion}?d={deviceId}&v={timestamp}
*
* @param patchVersion patchVersion
* @param filePath the target patch file path
* @param callback the request callback
*/
public void download(final String patchVersion,
final String filePath,
final DataFetcher.DataCallback<? super File> callback) {
Preconditions.checkNotEmpty(patchVersion);
final String url = Uri.parse(this.host)
.buildUpon()
.appendPath(this.appKey)
.appendPath(this.appVersion)
.appendPath(String.format("file%s", patchVersion))
.appendQueryParameter("d", versionUtils.id())
.appendQueryParameter("v", String.valueOf(System.currentTimeMillis()))
.build().toString();
TinkerClientUrl tkClientUrl = new TinkerClientUrl.Builder().url(url).build();
final DataFetcher<InputStream> dataFetcher = loader.buildLoadData(tkClientUrl);
dataFetcher.loadData(new DataFetcher.DataCallback<InputStream>() {
@Override
public void onDataReady(InputStream data) {
if (callback == null) {
return;
}
try {
callback.onDataReady(ServerUtils.readStreamToFile(data, filePath));
} catch (Exception e) {
callback.onLoadFailed(e);
} finally {
dataFetcher.cleanup();
}
}
@Override
public void onLoadFailed(Exception e) {
if (callback == null) {
return;
}
try {
callback.onLoadFailed(e);
} finally {
dataFetcher.cleanup();
}
}
});
}
/**
* report download success http://stat.tinkerpatch.com/succDownload.php
* @param patchVersion patchVersion
*/
public void reportDownloadSuccess(Integer patchVersion) {
reportSuccess(patchVersion, REPORT_DOWNLOAD_SUCCESS_URL);
}
/**
* report apply success http://stat.tinkerpatch.com/succ.php
* @param patchVersion patchVersion
*/
public void reportApplySuccess(Integer patchVersion) {
reportSuccess(patchVersion, REPORT_APPLY_SUCCESS_URL);
}
/**
* Report success to back
* @param patchVersion patchVersion
* @param reportUrl report url
*/
private void reportSuccess(final Integer patchVersion, final String reportUrl) {
Uri.Builder urlBuilder = Uri.parse(reportUrl).buildUpon();
final String url = urlBuilder.build().toString();
SuccessReport report = new SuccessReport(this.appKey, this.appVersion, String.valueOf(patchVersion));
TinkerClientUrl tkClientUrl = new TinkerClientUrl.Builder()
.url(url)
.body(report.toEncodeForm())
.method("POST").build();
final DataFetcher<InputStream> dataFetcher = loader.buildLoadData(tkClientUrl);
dataFetcher.loadData(new DataFetcher.DataCallback<InputStream>() {
@Override
public void onDataReady(InputStream data) {
TinkerLog.d(TAG,
String.format("reportSuccess successfully, url:%s, response: %s",
reportUrl,
ServerUtils.readStreamToString(data, ServerUtils.CHARSET))
);
}
@Override
public void onLoadFailed(Exception e) {
TinkerLog.e(TAG, "reportSuccess error, url: " + reportUrl, e);
}
});
}
/**
* Report fail to tinkerpatch backend
* @param patchVersion patchVersion
* @param errCode errCode
*/
public void reportFail(Integer patchVersion, Integer errCode) {
Uri.Builder urlBuilder = Uri.parse(REPORT_FAIL_URL).buildUpon();
final String url = urlBuilder.build().toString();
FailReport report = new FailReport(this.appKey, this.appVersion, String.valueOf(patchVersion), errCode);
TinkerClientUrl tkClientUrl = new TinkerClientUrl.Builder()
.url(url)
.body(report.toEncodeForm())
.method("POST").build();
final DataFetcher<InputStream> dataFetcher = loader.buildLoadData(tkClientUrl);
dataFetcher.loadData(new DataFetcher.DataCallback<InputStream>() {
@Override
public void onDataReady(InputStream data) {
TinkerLog.d(TAG, "reportFail successfully:"
+ ServerUtils.readStreamToString(data, ServerUtils.CHARSET));
}
@Override
public void onLoadFailed(Exception e) {
TinkerLog.e(TAG, "reportSuccess error", e);
}
});
}
/**
* 请求动态配置文件。
* 请求http://{Host}/c/{appKey}?d={deviceId}&v={timestamp}
*/
public void getDynamicConfig(final DataFetcher.DataCallback<String> callback) {
final String url = Uri.parse(this.host)
.buildUpon()
.appendPath("c")
.appendPath(this.appKey)
.appendQueryParameter("d", versionUtils.id())
.appendQueryParameter("v", String.valueOf(System.currentTimeMillis()))
.build().toString();
TinkerClientUrl tkClientUrl = new TinkerClientUrl.Builder().url(url).build();
final DataFetcher<InputStream> dataFetcher = loader.buildLoadData(tkClientUrl);
dataFetcher.loadData(new DataFetcher.DataCallback<InputStream>() {
@Override
public void onDataReady(InputStream data) {
if (callback == null) {
TinkerLog.e(TAG, "[succ] getDynamicConfig's callback is null!");
return;
}
try {
String response = ServerUtils.readStreamToString(data, ServerUtils.CHARSET);
callback.onDataReady(response);
} catch (Exception e) {
callback.onLoadFailed(e);
} finally {
dataFetcher.cleanup();
}
}
@Override
public void onLoadFailed(Exception e) {
if (callback == null) {
TinkerLog.e(TAG, "[fail] getDynamicConfig's callback is null!");
return;
}
try {
callback.onLoadFailed(e);
} finally {
dataFetcher.cleanup();
}
}
});
}
/**
* Get current patch version
*
* @return patch version
*/
public Integer getCurrentPatchVersion() {
return versionUtils.getPatchVersion();
}
public String getCurrentPatchMd5() {
return versionUtils.getPatchMd5();
}
public String getAppVersion() {
return appVersion;
}
public String getAppKey() {
return appKey;
}
public String getHost() {
return host;
}
public boolean isDebug() {
return debug;
}
public Conditions getConditions() {
return conditions;
}
static class Builder {
private static final String HOST_URL = "http://q.tinkerpatch.com";
private String appVersion;
private String appKey;
private String host;
private Boolean debug;
private Conditions conditions;
private UrlConnectionUrlLoader loader;
private VersionUtils versionUtils;
TinkerClientAPI.Builder host(String host) {
this.host = host;
return this;
}
TinkerClientAPI.Builder appKey(String appKey) {
this.appKey = appKey;
return this;
}
TinkerClientAPI.Builder appVersion(String appVersion) {
this.appVersion = appVersion;
return this;
}
TinkerClientAPI.Builder debug(boolean debug) {
this.debug = debug;
return this;
}
TinkerClientAPI.Builder conditions(Context context) {
this.conditions = new Conditions();
return this;
}
TinkerClientAPI.Builder urlLoader(UrlConnectionUrlLoader loader) {
this.loader = loader;
return this;
}
TinkerClientAPI.Builder versionUtils(VersionUtils versionUtils) {
this.versionUtils = versionUtils;
return this;
}
void makeDefault() {
if (TextUtils.isEmpty(host)) {
this.host = HOST_URL;
}
if (this.loader == null) {
this.loader = new UrlConnectionUrlLoader();
}
if (TextUtils.isEmpty(this.appKey) || TextUtils.isEmpty(this.appVersion)) {
throw new RuntimeException("You need setup Appkey and AppVersion");
}
if (this.conditions == null) {
throw new RuntimeException("You need init conditions property");
}
}
public TinkerClientAPI build() {
makeDefault();
return new TinkerClientAPI(
this.appKey, this.appVersion, this.host, this.debug,
this.conditions, this.loader, this.versionUtils
);
}
}
}