1
0
mirror of https://github.com/NekoX-Dev/NekoX.git synced 2024-12-16 14:10:31 +01:00

Revert okhttp usages

This commit is contained in:
世界 2020-12-29 22:33:42 +08:00
parent 287f1bd018
commit e53973b7de
No known key found for this signature in database
GPG Key ID: CD109927C34A63C4
10 changed files with 191 additions and 229 deletions

View File

@ -83,6 +83,7 @@ dependencies {
implementation 'cn.hutool:hutool-core:5.5.5'
implementation 'cn.hutool:hutool-crypto:5.5.5'
implementation 'cn.hutool:hutool-http:5.5.5'
implementation 'com.jakewharton:process-phoenix:2.0.0'

View File

@ -174,6 +174,11 @@ public class ConnectionsManager extends BaseController {
deviceModel = Build.MANUFACTURER + Build.MODEL;
PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0);
appVersion = pInfo.versionName + " (" + pInfo.versionCode + ")";
if (BuildVars.DEBUG_PRIVATE_VERSION) {
appVersion += " pbeta";
} else if (BuildVars.DEBUG_VERSION) {
appVersion += " beta";
}
systemVersion = "SDK " + Build.VERSION.SDK_INT;
} catch (Exception e) {
systemLangCode = "en";
@ -203,15 +208,7 @@ public class ConnectionsManager extends BaseController {
int timezoneOffset = (TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings()) / 1000;
int layer = MessagesController.getMainSettings(currentAccount).getInt("layer", TLRPC.LAYER);
if (layer != TLRPC.LAYER) {
FileLog.d("use custom layer " + layer);
}
init(BuildVars.BUILD_VERSION, layer, BuildConfig.APP_ID, deviceModel, systemVersion, appVersion, langCode, systemLangCode, configPath, FileLog.getNetworkLogPath(), pushString, fingerprint, timezoneOffset, getUserConfig().getClientUserId(), enablePushConnection);
init(BuildVars.BUILD_VERSION, TLRPC.LAYER, BuildConfig.APP_ID, deviceModel, systemVersion, appVersion, langCode, systemLangCode, configPath, FileLog.getNetworkLogPath(), pushString, fingerprint, timezoneOffset, getUserConfig().getClientUserId(), enablePushConnection);
}
public boolean isPushConnectionEnabled() {
@ -257,9 +254,9 @@ public class ConnectionsManager extends BaseController {
public int sendRequest(final TLObject object, final RequestDelegate onComplete, final QuickAckDelegate onQuickAck, final WriteToSocketDelegate onWriteToSocket, final int flags, final int datacenterId, final int connetionType, final boolean immediate) {
final int requestToken = lastRequestToken.getAndIncrement();
UIUtil.runOnIoDispatcher(() -> {
Utilities.stageQueue.postRunnable(() -> {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("send request " + object.getClass().getSimpleName() + " with token = " + requestToken);
FileLog.d("send request " + object + " with token = " + requestToken);
}
try {
NativeByteBuffer buffer = new NativeByteBuffer(object.getObjectSize());
@ -279,14 +276,14 @@ public class ConnectionsManager extends BaseController {
error.code = errorCode;
error.text = errorText;
if (BuildVars.LOGS_ENABLED) {
FileLog.e(object.getClass().getSimpleName() + " got error " + error.code + " " + error.text + " with token = " + requestToken);
FileLog.e(object + " got error " + error.code + " " + error.text);
}
}
if (resp != null) {
resp.networkType = networkType;
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("java received " + resp + " error = " + (error == null ? "null" : (error.code + ": " + error.text)));
FileLog.d("java received " + resp + " error = " + error);
}
final TLObject finalResponse = resp;
final TLRPC.TL_error finalError = error;
@ -350,10 +347,12 @@ public class ConnectionsManager extends BaseController {
public void init(int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String systemLangCode, String configPath, String logPath, String regId, String cFingerprint, int timezoneOffset, int userId, boolean enablePushConnection) {
if (SharedConfig.proxyEnabled && SharedConfig.currentProxy != null) {
if (SharedConfig.currentProxy instanceof SharedConfig.ExternalSocks5Proxy) {
((SharedConfig.ExternalSocks5Proxy) SharedConfig.currentProxy).start();
}
native_setProxySettings(currentAccount, SharedConfig.currentProxy.address, SharedConfig.currentProxy.port, SharedConfig.currentProxy.username, SharedConfig.currentProxy.password, SharedConfig.currentProxy.secret);
}
String installer = "";
try {
installer = ApplicationLoader.applicationContext.getPackageManager().getInstallerPackageName(ApplicationLoader.applicationContext.getPackageName());

View File

@ -45,8 +45,6 @@ import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
@ -61,19 +59,25 @@ import org.telegram.messenger.ImageReceiver;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.TLRPC;
import tw.nekomimi.nekogram.utils.HttpUtil;
import tw.nekomimi.nekogram.utils.ThreadUtil;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
public class WebPlayerView extends ViewGroup implements VideoPlayer.VideoPlayerDelegate, AudioManager.OnAudioFocusChangeListener {
@ -441,48 +445,139 @@ public class WebPlayerView extends ViewGroup implements VideoPlayer.VideoPlayerD
}
protected String downloadUrlContent(AsyncTask parentTask, String url, HashMap<String, String> headers, boolean tryGzip) {
OkHttpClient client = HttpUtil.getOkHttpClientWithCurrProxy().newBuilder()
.followRedirects(true)
.followSslRedirects(true)
.build();
Request.Builder request = new Request.Builder().url(url)
.header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/47.0 (Chrome)")
.header("Accept-Language", "en-us,en;q=0.5")
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.header("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
if (headers != null) {
for (Map.Entry<String, String> header : headers.entrySet()) {
request.addHeader(header.getKey(), header.getValue());
boolean canRetry = true;
InputStream httpConnectionStream = null;
boolean done = false;
StringBuilder result = null;
URLConnection httpConnection = null;
try {
URL downloadUrl = new URL(url);
httpConnection = downloadUrl.openConnection();
httpConnection.addRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/47.0 (Chrome)");
if (tryGzip) {
httpConnection.addRequestProperty("Accept-Encoding", "gzip, deflate");
}
httpConnection.addRequestProperty("Accept-Language", "en-us,en;q=0.5");
httpConnection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpConnection.addRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
if (headers != null) {
for (HashMap.Entry<String, String> entry : headers.entrySet()) {
httpConnection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
httpConnection.setConnectTimeout(5000);
httpConnection.setReadTimeout(5000);
if (httpConnection instanceof HttpURLConnection) {
HttpURLConnection httpURLConnection = (HttpURLConnection) httpConnection;
httpURLConnection.setInstanceFollowRedirects(true);
int status = httpURLConnection.getResponseCode();
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) {
String newUrl = httpURLConnection.getHeaderField("Location");
String cookies = httpURLConnection.getHeaderField("Set-Cookie");
downloadUrl = new URL(newUrl);
httpConnection = downloadUrl.openConnection();
httpConnection.setRequestProperty("Cookie", cookies);
httpConnection.addRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/47.0 (Chrome)");
if (tryGzip) {
httpConnection.addRequestProperty("Accept-Encoding", "gzip, deflate");
}
httpConnection.addRequestProperty("Accept-Language", "en-us,en;q=0.5");
httpConnection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpConnection.addRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
if (headers != null) {
for (HashMap.Entry<String, String> entry : headers.entrySet()) {
httpConnection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
}
}
httpConnection.connect();
if (tryGzip) {
try {
httpConnectionStream = new GZIPInputStream(httpConnection.getInputStream());
} catch (Exception e) {
try {
if (httpConnectionStream != null) {
httpConnectionStream.close();
}
} catch (Exception ignore) {
}
httpConnection = downloadUrl.openConnection();
httpConnection.connect();
httpConnectionStream = httpConnection.getInputStream();
}
} else {
httpConnectionStream = httpConnection.getInputStream();
}
} catch (Throwable e) {
if (e instanceof SocketTimeoutException) {
if (ApplicationLoader.isNetworkOnline()) {
canRetry = false;
}
} else if (e instanceof UnknownHostException) {
canRetry = false;
} else if (e instanceof SocketException) {
if (e.getMessage() != null && e.getMessage().contains("ECONNRESET")) {
canRetry = false;
}
} else if (e instanceof FileNotFoundException) {
canRetry = false;
}
FileLog.e(e);
}
if (tryGzip) {
request.addHeader("Accept-Encoding", "gzip, deflate");
}
int count = 0;
do {
if (canRetry) {
try {
return client.newCall(request.build()).execute().body().string();
if (httpConnection instanceof HttpURLConnection) {
int code = ((HttpURLConnection) httpConnection).getResponseCode();
if (code != HttpURLConnection.HTTP_OK && code != HttpURLConnection.HTTP_ACCEPTED && code != HttpURLConnection.HTTP_NOT_MODIFIED) {
//canRetry = false;
}
}
} catch (Exception e) {
FileLog.e(e);
}
count ++;
ThreadUtil.sleep(1000);
} while (count < 3);
return null;
if (httpConnectionStream != null) {
try {
byte[] data = new byte[1024 * 32];
while (true) {
if (parentTask.isCancelled()) {
break;
}
try {
int read = httpConnectionStream.read(data);
if (read > 0) {
if (result == null) {
result = new StringBuilder();
}
result.append(new String(data, 0, read, StandardCharsets.UTF_8));
} else if (read == -1) {
done = true;
break;
} else {
break;
}
} catch (Exception e) {
FileLog.e(e);
break;
}
}
} catch (Throwable e) {
FileLog.e(e);
}
}
try {
if (httpConnectionStream != null) {
httpConnectionStream.close();
}
} catch (Throwable e) {
FileLog.e(e);
}
}
return done ? result.toString() : null;
}
private class YoutubeVideoTask extends AsyncTask<Void, Void, String[]> {

View File

@ -1,11 +1,7 @@
package tw.nekomimi.nekogram.sub;
import android.os.Build;
import androidx.annotation.NonNull;
import com.google.android.gms.common.util.HttpUtils;
import org.dizitart.no2.Document;
import org.dizitart.no2.mapper.Mappable;
import org.dizitart.no2.mapper.NitriteMapper;
@ -21,7 +17,7 @@ import java.util.List;
import java.util.Map;
import cn.hutool.core.util.StrUtil;
import tw.nekomimi.nekogram.utils.HttpUtil;
import cn.hutool.http.HttpUtil;
import tw.nekomimi.nekogram.utils.ProxyUtil;
@Index("id")
@ -55,15 +51,7 @@ public class SubInfo implements Mappable {
try {
String source;
if (Build.VERSION.SDK_INT < 21) {
source = cn.hutool.http.HttpUtil.get(url);
} else {
source = HttpUtil.get(url);
}
return ProxyUtil.parseProxies(source);
return ProxyUtil.parseProxies(HttpUtil.get(url));
} catch (Exception e) {

View File

@ -1,15 +1,12 @@
package tw.nekomimi.nekogram.transtale.source
import cn.hutool.core.util.StrUtil
import okhttp3.Request
import org.json.JSONObject
import org.telegram.messenger.LocaleController
import org.telegram.messenger.R
import tw.nekomimi.nekogram.NekoConfig
import tw.nekomimi.nekogram.transtale.TransUtils
import tw.nekomimi.nekogram.transtale.Translator
import tw.nekomimi.nekogram.utils.HttpUtil
import tw.nekomimi.nekogram.utils.applyUserAgent
object GoogleAppTranslator : Translator {

View File

@ -1,14 +1,12 @@
package tw.nekomimi.nekogram.transtale.source
import cn.hutool.core.util.StrUtil
import okhttp3.FormBody
import okhttp3.Request
import cn.hutool.http.HttpUtil
import org.json.JSONObject
import org.telegram.messenger.LocaleController
import org.telegram.messenger.R
import tw.nekomimi.nekogram.NekoConfig
import tw.nekomimi.nekogram.transtale.Translator
import tw.nekomimi.nekogram.utils.HttpUtil
object GoogleCloudTranslator : Translator {
@ -22,31 +20,22 @@ object GoogleCloudTranslator : Translator {
if (StrUtil.isBlank(NekoConfig.googleCloudTranslateKey)) error("Missing Cloud Translate Key")
val request = Request.Builder()
.url("https://translation.googleapis.com/language/translate/v2")
.post(FormBody.Builder()
.add("q", query)
.add("target", to)
.add("format", "text")
.add("key", NekoConfig.googleCloudTranslateKey)
.apply {
if (from != "auto") add("source", from)
}
.build()).build()
val response = HttpUtil.createPost("https://translation.googleapis.com/language/translate/v2")
.form("q", query)
.form("target", to)
.form("format", "text")
.form("key", NekoConfig.googleCloudTranslateKey)
.apply {
if (from != "auto") form("source", from)
}.execute()
val response = runCatching {
HttpUtil.okHttpClient.newCall(request).execute()
}.recoverCatching {
HttpUtil.okHttpClientWithCurrProxy.newCall(request).execute()
}.getOrThrow()
if (response.status != 200) {
if (response.code != 200) {
error("HTTP ${response.code} : ${response.body?.string()}")
error("HTTP ${response.status} : ${response.body()}")
}
var respObj = JSONObject(response.body!!.string())
var respObj = JSONObject(response.body())
if (respObj.isNull("data")) error(respObj.toString(4))

View File

@ -1,12 +1,10 @@
package tw.nekomimi.nekogram.transtale.source
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import cn.hutool.http.HttpUtil
import org.json.JSONObject
import org.telegram.messenger.LocaleController
import org.telegram.messenger.R
import tw.nekomimi.nekogram.transtale.Translator
import tw.nekomimi.nekogram.utils.HttpUtil
import tw.nekomimi.nekogram.utils.applyUserAgent
object LingoTranslator : Translator {
@ -19,33 +17,23 @@ object LingoTranslator : Translator {
}
val request = Request.Builder()
.url("https://api.interpreter.caiyunai.com/v1/translator")
val response = HttpUtil.createPost("https://api.interpreter.caiyunai.com/v1/translator")
.header("Content-Type", "application/json; charset=UTF-8")
.header("X-Authorization", "token 9sdftiq37bnv410eon2l") // 白嫖
.applyUserAgent()
.post(JSONObject().apply {
.form("source", query)
.form("trans_type", "${from}2$to")
.form("request_id", System.currentTimeMillis().toString())
.form("detect", true)
.execute()
put("source", query)
put("trans_type", "${from}2$to")
put("request_id", System.currentTimeMillis().toString())
put("detect", true)
if (response.status != 200) {
}.toString().toRequestBody()).build()
val response = runCatching {
HttpUtil.okHttpClient.newCall(request).execute()
}.recoverCatching {
HttpUtil.okHttpClientWithCurrProxy.newCall(request).execute()
}.getOrThrow()
if (response.code != 200) {
error("HTTP ${response.code} : ${response.body?.string()}")
error("HTTP ${response.status} : ${response.body()}")
}
return JSONObject(response.body!!.string()).getString("target")
return JSONObject(response.body()).getString("target")
}

View File

@ -1,11 +1,9 @@
package tw.nekomimi.nekogram.transtale.source
import cn.hutool.core.lang.UUID
import okhttp3.FormBody
import okhttp3.Request
import cn.hutool.http.HttpUtil
import org.json.JSONObject
import tw.nekomimi.nekogram.transtale.Translator
import tw.nekomimi.nekogram.utils.HttpUtil
import tw.nekomimi.nekogram.utils.applyUserAgent
object YandexTranslator : Translator {
@ -16,29 +14,21 @@ object YandexTranslator : Translator {
val uuid2 = UUID.fastUUID().toString(true)
val request = Request.Builder()
.url("https://translate.yandex.net/api/v1/tr.json/translate?srv=android&uuid=$uuid&id=$uuid2-9-0")
val response = HttpUtil.createPost("https://translate.yandex.net/api/v1/tr.json/translate?srv=android&uuid=$uuid&id=$uuid2-9-0")
.applyUserAgent()
.post(FormBody.Builder()
.add("text", query)
.add("lang", if (from == "auto") to else "$from-$to")
.build()).build()
.form("text", query)
.form("lang", if (from == "auto") to else "$from-$to")
.execute()
val response = runCatching {
HttpUtil.okHttpClient.newCall(request).execute()
}.recoverCatching {
HttpUtil.okHttpClientWithCurrProxy.newCall(request).execute()
}.getOrThrow()
if (response.status != 200) {
if (response.code != 200) {
error("HTTP ${response.code} : ${response.body?.string()}")
error("HTTP ${response.status} : ${response.body()}")
}
val respObj = JSONObject(response.body!!.string())
val respObj = JSONObject(response.body())
if (respObj.optInt("code",-1) != 200) error(respObj.toString(4))
if (respObj.optInt("code", -1) != 200) error(respObj.toString(4))
return respObj.getJSONArray("text").getString(0)

View File

@ -1,5 +1,6 @@
package tw.nekomimi.nekogram.utils
import android.os.Build
import okhttp3.Dns
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
@ -20,10 +21,14 @@ open class DnsFactory : Dns {
init {
addProvider("https://mozilla.cloudflare-dns.com/dns-query")
addProvider("https://dns.google/dns-query")
addProvider("https://dns.twnic.tw/dns-query")
addProvider("https://dns.adguard.com/dns-query")
if (Build.VERSION.SDK_INT >= 21) {
addProvider("https://mozilla.cloudflare-dns.com/dns-query")
addProvider("https://dns.google/dns-query")
addProvider("https://dns.twnic.tw/dns-query")
addProvider("https://dns.adguard.com/dns-query")
}
}
}

View File

@ -1,102 +1,12 @@
package tw.nekomimi.nekogram.utils
import okhttp3.Dns
import okhttp3.OkHttpClient
import okhttp3.Request
import org.telegram.messenger.SharedConfig
import java.net.InetSocketAddress
import java.net.Proxy
import java.util.concurrent.TimeUnit
import cn.hutool.http.HttpRequest
fun Request.Builder.applyUserAgent(): Request.Builder {
fun HttpRequest.applyUserAgent(): HttpRequest {
header("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A5297c Safari/602.1")
header("X-Requested-With", "XMLHttpRequest")
return this
}
object HttpUtil {
@JvmField
val okHttpClient = OkHttpClient.Builder()
.dns(DnsFactory)
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build()
val okHttpClientNoDoh = okHttpClient.newBuilder()
.dns(Dns.SYSTEM)
.build()
@JvmStatic
val okHttpClientWithCurrProxy: OkHttpClient
get() {
return if (!SharedConfig.proxyEnabled || SharedConfig.currentProxy?.secret != null) {
okHttpClient
} else {
okHttpClient.newBuilder()
.proxy(Proxy(Proxy.Type.SOCKS, InetSocketAddress(SharedConfig.currentProxy.address, SharedConfig.currentProxy.port)))
.build()
}
}
@JvmStatic
@JvmOverloads
fun get(url: String, client: OkHttpClient = okHttpClient): String {
val request = Request.Builder().url(url)
.applyUserAgent()
.build()
okHttpClient.newCall(request).execute().apply {
val body = body
return body?.string() ?: error("HTTP ERROR $code")
}
}
@JvmStatic
fun getNoDoh(url: String): String {
val request = Request.Builder().url(url)
.applyUserAgent()
.build()
okHttpClientNoDoh.newCall(request).execute().apply {
val body = body
return body?.string() ?: error("HTTP ERROR $code")
}
}
@JvmStatic
fun getByteArray(url: String): ByteArray {
val request = Request.Builder()
.url(url)
.applyUserAgent()
.build()
okHttpClient.newCall(request).execute().apply {
return body?.bytes() ?: error("HTTP ERROR $code")
}
}
}