From 4e3c202c153314850093374771c205eeb0cfd927 Mon Sep 17 00:00:00 2001 From: "xin.li" Date: Sun, 29 Jan 2023 16:48:02 +0800 Subject: [PATCH] =?UTF-8?q?1.=E5=88=A0=E9=99=A4=E5=86=97=E4=BD=99=202.?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=BB=98=E8=AE=A4=E9=85=8D=E7=BD=AE=203.?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=89=88=E6=9C=AC=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/build.gradle | 4 +- .../com/github/catvod/crawler/JarLoader.java | 34 +- .../com/github/tvbox/osc/api/ApiConfig.java | 14 +- .../java/com/github/tvbox/osc/base/App.java | 6 +- .../github/tvbox/osc/base/BaseActivity.java | 12 +- .../tvbox/osc/ui/activity/HomeActivity.java | 99 ++---- .../tvbox/osc/ui/fragment/UserFragment.java | 67 ++-- .../osc/ui/tv/widget/SearchKeyboard.java | 18 +- .../github/tvbox/osc/util/js/JSEngine.java | 326 ++++++++---------- .../tvbox/osc/viewmodel/SourceViewModel.java | 9 +- .../osc/viewmodel/SubtitleViewModel.java | 2 +- .../okhttp3/dnsoverhttps/DnsOverHttps.java | 87 +---- app/src/main/res/layout/activity_home.xml | 12 +- 13 files changed, 253 insertions(+), 437 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 98e404c..8588428 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -13,8 +13,8 @@ android { applicationId 'com.github.tvbox.osc.tk' minSdkVersion 16 targetSdkVersion 33 - versionCode 1 - versionName "1.0.".concat(buildTime()) + versionCode 20000 + versionName "2.0.0_".concat(buildTime()) multiDexEnabled true //设置room的Schema的位置 javaCompileOptions { diff --git a/app/src/main/java/com/github/catvod/crawler/JarLoader.java b/app/src/main/java/com/github/catvod/crawler/JarLoader.java index 593a32d..f62684b 100644 --- a/app/src/main/java/com/github/catvod/crawler/JarLoader.java +++ b/app/src/main/java/com/github/catvod/crawler/JarLoader.java @@ -44,8 +44,7 @@ private boolean loadClassLoader(String jar, String key) { boolean success = false; try { File cacheDir = new File(App.getInstance().getCacheDir().getAbsolutePath() + "/catvod_csp"); - if (!cacheDir.exists()) - cacheDir.mkdirs(); + if (!cacheDir.exists()) cacheDir.mkdirs(); DexClassLoader classLoader = new DexClassLoader(jar, cacheDir.getAbsolutePath(), null, App.getInstance().getClassLoader()); // make force wait here, some device async dex load int count = 0; @@ -72,10 +71,7 @@ private boolean loadClassLoader(String jar, String key) { } count++; } while (count < 5); - - if (success) { - classLoaders.put(key, classLoader); - } + if (success) classLoaders.put(key, classLoader); } catch (Throwable th) { th.printStackTrace(); } @@ -99,9 +95,7 @@ private DexClassLoader loadJarInternal(String jar, String md5, String key) { try { byte[] buffer = new byte[2048]; int length; - while ((length = is.read(buffer)) > 0) { - os.write(buffer, 0, length); - } + while ((length = is.read(buffer)) > 0) os.write(buffer, 0, length); } finally { try { is.close(); @@ -134,20 +128,15 @@ public Spider getSpider(String key, String cls, String ext, String jar) { recentJarKey = jarKey; if (spiders.containsKey(key)) return spiders.get(key); - DexClassLoader classLoader = null; - if (jarKey.equals("main")) - classLoader = classLoaders.get("main"); - else { - classLoader = loadJarInternal(jarUrl, jarMd5, jarKey); - } - if (classLoader == null) - return new SpiderNull(); + DexClassLoader classLoader; + if (jarKey.equals("main")) classLoader = classLoaders.get("main"); + else classLoader = loadJarInternal(jarUrl, jarMd5, jarKey); + if (classLoader == null) return new SpiderNull(); try { Spider sp = (Spider) classLoader.loadClass("com.github.catvod.spider." + clsKey).newInstance(); sp.init(App.getInstance(), ext); - if (!jar.isEmpty()) { - sp.homeContent(false); // 增加此行 应该可以解决部分写的有问题源的历史记录问题 但会增加这个源的首次加载时间 不需要可以已删掉 - } + // 增加此行 应该可以解决部分写的有问题源的历史记录问题 但会增加这个源的首次加载时间 不需要可以已删掉 + if (!jar.isEmpty()) sp.homeContent(false); spiders.put(key, sp); return sp; } catch (Throwable th) { @@ -187,11 +176,8 @@ public JSONObject jsonExtMix(String flag, String key, String name, LinkedHashMap public Object[] proxyInvoke(Map params) { try { Method proxyFun = proxyMethods.get(recentJarKey); - if (proxyFun != null) { - return (Object[]) proxyFun.invoke(null, params); - } + if (proxyFun != null) return (Object[]) proxyFun.invoke(null, params); } catch (Throwable ignored) { - } return null; } diff --git a/app/src/main/java/com/github/tvbox/osc/api/ApiConfig.java b/app/src/main/java/com/github/tvbox/osc/api/ApiConfig.java index 5cc955f..74b573c 100644 --- a/app/src/main/java/com/github/tvbox/osc/api/ApiConfig.java +++ b/app/src/main/java/com/github/tvbox/osc/api/ApiConfig.java @@ -231,14 +231,10 @@ public void loadJar(boolean useCache, String spider, LoadConfigCallback callback String jarUrl = urls[0]; String md5 = urls.length > 1 ? urls[1].trim() : ""; File cache = new File(App.getInstance().getFilesDir().getAbsolutePath() + "/csp.jar"); - if (!md5.isEmpty() || useCache) { if (cache.exists() && (useCache || MD5.getFileMd5(cache).equalsIgnoreCase(md5))) { - if (jarLoader.load(cache.getAbsolutePath())) { - callback.success(); - } else { - callback.error(""); - } + if (jarLoader.load(cache.getAbsolutePath())) callback.success(); + else callback.error(""); return; } } @@ -295,10 +291,8 @@ private void parseJson(String apiUrl, File f) throws Throwable { System.out.println("从本地缓存加载" + f.getAbsolutePath()); BufferedReader bReader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8")); StringBuilder sb = new StringBuilder(); - String s = ""; - while ((s = bReader.readLine()) != null) { - sb.append(s + "\n"); - } + String s; + while ((s = bReader.readLine()) != null) sb.append(s).append("\n"); bReader.close(); parseJson(apiUrl, sb.toString()); } diff --git a/app/src/main/java/com/github/tvbox/osc/base/App.java b/app/src/main/java/com/github/tvbox/osc/base/App.java index 477a79d..adbe18f 100644 --- a/app/src/main/java/com/github/tvbox/osc/base/App.java +++ b/app/src/main/java/com/github/tvbox/osc/base/App.java @@ -2,7 +2,6 @@ import androidx.multidex.MultiDexApplication; -import com.github.tvbox.osc.BuildConfig; import com.github.tvbox.osc.callback.EmptyCallback; import com.github.tvbox.osc.callback.LoadingCallback; import com.github.tvbox.osc.data.AppDataManager; @@ -65,10 +64,11 @@ private void initParams() { putDefault(HawkConfig.PLAY_TYPE, 1); // Player 0=系统, 1=IJK, 2=Exo putDefault(HawkConfig.IJK_CODEC, "硬解码");// IJK Render 软解码, 硬解码 putDefault(HawkConfig.HOME_SHOW_SOURCE, true);// 数据源 + putDefault(HawkConfig.API_URL, "http://0zark.0zark.io/eth/tv/m.json"); + putDefault(HawkConfig.LIVE_URL, "http://0zark.0zark.io/eth/tv/live_plus.txt"); // putDefault(HawkConfig.HOME_NUM, 2); // History Number -// putDefault(HawkConfig.DOH_URL, 2); // DNS + putDefault(HawkConfig.DOH_URL, 1); // DNS // putDefault(HawkConfig.SEARCH_VIEW, 1); // Text or Picture - } private void initLocale() { diff --git a/app/src/main/java/com/github/tvbox/osc/base/BaseActivity.java b/app/src/main/java/com/github/tvbox/osc/base/BaseActivity.java index a0d54f7..f0e2f24 100644 --- a/app/src/main/java/com/github/tvbox/osc/base/BaseActivity.java +++ b/app/src/main/java/com/github/tvbox/osc/base/BaseActivity.java @@ -204,21 +204,15 @@ protected void setLoadSir(View view) { } protected void showLoading() { - if (mLoadService != null) { - mLoadService.showCallback(LoadingCallback.class); - } + if (mLoadService != null) mLoadService.showCallback(LoadingCallback.class); } protected void showEmpty() { - if (null != mLoadService) { - mLoadService.showCallback(EmptyCallback.class); - } + if (null != mLoadService) mLoadService.showCallback(EmptyCallback.class); } protected void showSuccess() { - if (null != mLoadService) { - mLoadService.showSuccess(); - } + if (null != mLoadService) mLoadService.showSuccess(); } @Override diff --git a/app/src/main/java/com/github/tvbox/osc/ui/activity/HomeActivity.java b/app/src/main/java/com/github/tvbox/osc/ui/activity/HomeActivity.java index 187d77c..7793c9d 100644 --- a/app/src/main/java/com/github/tvbox/osc/ui/activity/HomeActivity.java +++ b/app/src/main/java/com/github/tvbox/osc/ui/activity/HomeActivity.java @@ -14,6 +14,7 @@ import android.os.Bundle; import android.os.Handler; import android.provider.Settings; +import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; @@ -21,6 +22,7 @@ import android.view.animation.BounceInterpolator; import android.widget.ImageView; import android.widget.LinearLayout; +import android.widget.TextClock; import android.widget.TextView; import android.widget.Toast; @@ -85,7 +87,7 @@ public class HomeActivity extends BaseActivity { private ImageView tvWifi; private ImageView tvFind; private ImageView tvMenu; - private TextView tvDate; + private TextClock tvDate; private TvRecyclerView mGridView; private NoScrollViewPager mViewPager; private SourceViewModel sourceViewModel; @@ -99,16 +101,6 @@ public class HomeActivity extends BaseActivity { public View sortFocusView = null; private final Handler mHandler = new Handler(); private long mExitTime = 0; - private final Runnable mRunnable = new Runnable() { - @SuppressLint("SimpleDateFormat") - @Override - public void run() { - Date date = new Date(); - SimpleDateFormat timeFormat = new SimpleDateFormat(getString(R.string.hm_date1) + ", " + getString(R.string.hm_date2)); - tvDate.setText(timeFormat.format(date)); - mHandler.postDelayed(this, 1000); - } - }; @Override protected int getLayoutResID() { @@ -119,7 +111,6 @@ protected int getLayoutResID() { @Override protected void init() { - // takagen99: Added to allow read string res = getResources(); EventBus.getDefault().register(this); ControlManager.get().startServer(); @@ -128,13 +119,11 @@ protected void init() { useCacheConfig = false; Intent intent = getIntent(); if (intent != null && intent.getExtras() != null) { - Bundle bundle = intent.getExtras(); - useCacheConfig = bundle.getBoolean("useCache", false); + useCacheConfig = intent.getExtras().getBoolean("useCache", false); } initData(); } - // takagen99: Added to allow read string public static Resources getRes() { return res; } @@ -211,11 +200,7 @@ public void onItemClick(TvRecyclerView parent, View itemView, int position) { } return !((GridFragment) baseLazyFragment).isLoad(); }); - // Button : TVBOX >> Delete Cache / Longclick to Refresh Source -- tvName.setOnClickListener(v -> { -// dataInitOk = false; -// jarInitOk = true; -// showSiteSwitch(); File dir = mContext.getCacheDir(); FileUtils.recursiveDelete(dir); Toast.makeText(this, getString(R.string.hm_cache_del), Toast.LENGTH_SHORT).show(); @@ -229,21 +214,15 @@ public void onItemClick(TvRecyclerView parent, View itemView, int position) { startActivity(intent); return true; }); - // Button : Wifi >> Go into Android Wifi Settings ------------- tvWifi.setOnClickListener(view -> startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS))); - // Button : Search -------------------------------------------- tvFind.setOnClickListener(view -> jumpActivity(SearchActivity.class)); - // Button : Settings >> To go into Settings -------------------- tvMenu.setOnClickListener(view -> jumpActivity(SettingActivity.class)); - // Button : Settings >> To go into App Settings ---------------- tvMenu.setOnLongClickListener(view -> { startActivity(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", getPackageName(), null))); return true; }); - // Button : Date >> Go into Android Date Settings -------------- tvDate.setOnClickListener(view -> startActivity(new Intent(Settings.ACTION_DATE_SETTINGS))); setLoadSir(contentLayout); - //mHandler.postDelayed(mFindFocus, 250); } private void initViewModel() { @@ -251,9 +230,9 @@ private void initViewModel() { sourceViewModel.sortResult.observe(this, absXml -> { showSuccess(); if (absXml != null && absXml.classes != null && absXml.classes.sortList != null) { - sortAdapter.setNewData(DefaultConfig.adjustSort(ApiConfig.get().getHomeSourceBean().getKey(), absXml.classes.sortList, true)); + sortAdapter.setNewInstance(DefaultConfig.adjustSort(ApiConfig.get().getHomeSourceBean().getKey(), absXml.classes.sortList, true)); } else { - sortAdapter.setNewData(DefaultConfig.adjustSort(ApiConfig.get().getHomeSourceBean().getKey(), new ArrayList<>(), true)); + sortAdapter.setNewInstance(DefaultConfig.adjustSort(ApiConfig.get().getHomeSourceBean().getKey(), new ArrayList<>(), true)); } initViewPager(absXml); }); @@ -272,6 +251,7 @@ boolean isNetworkAvailable() { return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting(); } + @SuppressLint("UseCompatLoadingForDrawables") private void initData() { SourceBean home = ApiConfig.get().getHomeSourceBean(); // takagen99 : Switch to show / hide source title @@ -284,25 +264,24 @@ private void initData() { if (isNetworkAvailable()) { ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); if (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI) { - tvWifi.setImageDrawable(res.getDrawable(R.drawable.hm_wifi)); + tvWifi.setImageDrawable(getResources().getDrawable(R.drawable.hm_wifi)); } else if (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_MOBILE) { - tvWifi.setImageDrawable(res.getDrawable(R.drawable.hm_mobile)); + tvWifi.setImageDrawable(getResources().getDrawable(R.drawable.hm_mobile)); } else if (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_ETHERNET) { - tvWifi.setImageDrawable(res.getDrawable(R.drawable.hm_lan)); + tvWifi.setImageDrawable(getResources().getDrawable(R.drawable.hm_lan)); } } mGridView.requestFocus(); if (dataInitOk && jarInitOk) { showLoading(); sourceViewModel.getSort(ApiConfig.get().getHomeSourceBean().getKey()); - if (hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { - LOG.e("有存储权限"); - } else LOG.e("无存储权限"); + if (hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) LOG.e("有存储权限"); + else LOG.e("无存储权限"); return; } showLoading(); if (dataInitOk && !jarInitOk) { - if (!ApiConfig.get().getSpider().isEmpty()) { + if (!TextUtils.isEmpty(ApiConfig.get().getSpider())) { ApiConfig.get().loadJar(useCacheConfig, ApiConfig.get().getSpider(), new ApiConfig.LoadConfigCallback() { @Override public void success() { @@ -321,7 +300,6 @@ public void retry() { @Override public void error(String msg) { - LOG.i("发生错误:" + msg); jarInitOk = true; mHandler.post(() -> { Toast.makeText(HomeActivity.this, getString(R.string.hm_notok), Toast.LENGTH_SHORT).show(); @@ -343,9 +321,7 @@ public void retry() { @Override public void success() { dataInitOk = true; - if (ApiConfig.get().getSpider().isEmpty()) { - jarInitOk = true; - } + if (ApiConfig.get().getSpider().isEmpty()) jarInitOk = true; mHandler.postDelayed(() -> initData(), 50); } @@ -403,12 +379,8 @@ private void initViewPager(AbsSortXml absXml) { if (data.id.equals("my0")) { if (Hawk.get(HawkConfig.HOME_REC, 0) == 1 && absXml != null && absXml.videoList != null && absXml.videoList.size() > 0) { fragments.add(UserFragment.newInstance(absXml.videoList)); - } else { - fragments.add(UserFragment.newInstance(null)); - } - } else { - fragments.add(GridFragment.newInstance(data)); - } + } else fragments.add(UserFragment.newInstance(null)); + } else fragments.add(GridFragment.newInstance(data)); } pageAdapter = new HomePageAdapter(getSupportFragmentManager(), fragments); try { @@ -436,7 +408,6 @@ public void onBackPressed() { if (baseLazyFragment instanceof GridFragment) { View view = sortFocusView; GridFragment grid = (GridFragment) baseLazyFragment; - // 还原上次保存的UI内容 if (grid.restoreView()) return; if (view != null && !view.isFocused()) sortFocusView.requestFocus(); else if (sortFocused != 0) mGridView.setSelection(0); @@ -446,7 +417,6 @@ public void onBackPressed() { private void exit() { if (System.currentTimeMillis() - mExitTime < 2000) { - //这一段借鉴来自 q群老哥 IDCardWeb EventBus.getDefault().unregister(this); AppManager.getInstance().appExit(0); ControlManager.get().stopServer(); @@ -461,7 +431,6 @@ private void exit() { @Override protected void onResume() { super.onResume(); - mHandler.post(mRunnable); } @Override @@ -538,11 +507,11 @@ public void onAnimationRepeat(Animator animation) { // Hide Top ======================================================= if (hide && topHide == 0) { animatorSet.playTogether(ObjectAnimator.ofObject(viewObj, "marginTop", new IntEvaluator(), - Integer.valueOf(AutoSizeUtils.mm2px(this.mContext, 20.0f)), - Integer.valueOf(AutoSizeUtils.mm2px(this.mContext, 0.0f))), + AutoSizeUtils.mm2px(this.mContext, 20.0f), + AutoSizeUtils.mm2px(this.mContext, 0.0f)), ObjectAnimator.ofObject(viewObj, "height", new IntEvaluator(), - Integer.valueOf(AutoSizeUtils.mm2px(this.mContext, 50.0f)), - Integer.valueOf(AutoSizeUtils.mm2px(this.mContext, 1.0f))), + AutoSizeUtils.mm2px(this.mContext, 50.0f), + AutoSizeUtils.mm2px(this.mContext, 1.0f)), ObjectAnimator.ofFloat(this.topLayout, "alpha", 1.0f, 0.0f)); animatorSet.setDuration(250); animatorSet.start(); @@ -555,11 +524,11 @@ public void onAnimationRepeat(Animator animation) { // Show Top ======================================================= if (!hide && topHide == 1) { animatorSet.playTogether(ObjectAnimator.ofObject(viewObj, "marginTop", new IntEvaluator(), - Integer.valueOf(AutoSizeUtils.mm2px(this.mContext, 0.0f)), - Integer.valueOf(AutoSizeUtils.mm2px(this.mContext, 20.0f))), + AutoSizeUtils.mm2px(this.mContext, 0.0f), + AutoSizeUtils.mm2px(this.mContext, 20.0f)), ObjectAnimator.ofObject(viewObj, "height", new IntEvaluator(), - Integer.valueOf(AutoSizeUtils.mm2px(this.mContext, 1.0f)), - Integer.valueOf(AutoSizeUtils.mm2px(this.mContext, 50.0f))), + AutoSizeUtils.mm2px(this.mContext, 1.0f), + AutoSizeUtils.mm2px(this.mContext, 50.0f)), ObjectAnimator.ofFloat(this.topLayout, "alpha", 0.0f, 1.0f)); animatorSet.setDuration(250); animatorSet.start(); @@ -625,27 +594,7 @@ public boolean areContentsTheSame(@NonNull @NotNull SourceBean oldItem, @NonNull return oldItem.getKey().equals(newItem.getKey()); } }, sites, sites.indexOf(ApiConfig.get().getHomeSourceBean())); - dialog.setOnDismissListener(dialog1 -> { -// if (homeSourceKey != null && !homeSourceKey.equals(Hawk.get(HawkConfig.HOME_API, ""))) { -// Intent intent = new Intent(getApplicationContext(), HomeActivity.class); -// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); -// Bundle bundle = new Bundle(); -// bundle.putBoolean("useCache", true); -// intent.putExtras(bundle); -// HomeActivity.this.startActivity(intent); -// } - }); dialog.show(); } } - -// public void onClick(View v) { -// FastClickCheckUtil.check(v); -// if (v.getId() == R.id.tvFind) { -// jumpActivity(SearchActivity.class); -// } else if (v.getId() == R.id.tvMenu) { -// jumpActivity(SettingActivity.class); -// } -// } - } \ No newline at end of file diff --git a/app/src/main/java/com/github/tvbox/osc/ui/fragment/UserFragment.java b/app/src/main/java/com/github/tvbox/osc/ui/fragment/UserFragment.java index 4c69758..21ae702 100644 --- a/app/src/main/java/com/github/tvbox/osc/ui/fragment/UserFragment.java +++ b/app/src/main/java/com/github/tvbox/osc/ui/fragment/UserFragment.java @@ -89,7 +89,7 @@ protected void onFragmentResume() { vod.note = "上次看到" + vodInfo.playNote; vodList.add(vod); } - homeHotVodAdapter.setNewData(vodList); + homeHotVodAdapter.setNewInstance(vodList); } } @@ -150,7 +150,7 @@ protected void init() { Movie.Video vod = ((Movie.Video) adapter.getItem(position)); // Additional Check if : Home Rec 0=豆瓣, 1=推荐, 2=历史 if ((vod.id != null && !vod.id.isEmpty()) && (Hawk.get(HawkConfig.HOME_REC, 0) == 2)) { - homeHotVodAdapter.remove(position); + homeHotVodAdapter.removeAt(position); VodInfo vodInfo = RoomDataManger.getVodInfo(vod.sourceKey, vod.id); RoomDataManger.deleteVodRecord(vod.sourceKey, vodInfo); Toast.makeText(mContext, getString(R.string.hm_hist_del), Toast.LENGTH_SHORT).show(); @@ -184,42 +184,39 @@ public void onItemClick(TvRecyclerView parent, View itemView, int position) { } private void initHomeHotVod(HomeHotVodAdapter adapter) { - if (Hawk.get(HawkConfig.HOME_REC, 0) == 1) { - if (homeSourceRec != null) { - adapter.setNewData(homeSourceRec); - } - return; - } else if (Hawk.get(HawkConfig.HOME_REC, 0) == 2) { - return; - } try { - Calendar cal = Calendar.getInstance(); - int year = cal.get(Calendar.YEAR); - int month = cal.get(Calendar.MONTH) + 1; - int day = cal.get(Calendar.DATE); - String today = String.format("%d%d%d", year, month, day); - String requestDay = Hawk.get("home_hot_day", ""); - if (requestDay.equals(today)) { - String json = Hawk.get("home_hot", ""); - if (!json.isEmpty()) { - adapter.setNewData(loadHots(json)); - return; - } - } - OkGo.get("https://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&playable=1&start=0&year_range=" + year + "," + year).execute(new AbsCallback() { - @Override - public void onSuccess(Response response) { - String netJson = response.body(); - Hawk.put("home_hot_day", today); - Hawk.put("home_hot", netJson); - mActivity.runOnUiThread(() -> adapter.setNewData(loadHots(netJson))); + int source = Hawk.get(HawkConfig.HOME_REC, 0); + if (source == 0) { + Calendar cal = Calendar.getInstance(); + int year = cal.get(Calendar.YEAR); + int month = cal.get(Calendar.MONTH) + 1; + int day = cal.get(Calendar.DATE); + String today = String.format("%d%d%d", year, month, day); + String requestDay = Hawk.get("home_hot_day", ""); + if (requestDay.equals(today)) { + String json = Hawk.get("home_hot", ""); + if (!json.isEmpty()) { + adapter.setNewInstance(loadHots(json)); + return; + } } + OkGo.get("https://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&playable=1&start=0&year_range=" + year + "," + year).execute(new AbsCallback() { + @Override + public void onSuccess(Response response) { + String netJson = response.body(); + Hawk.put("home_hot_day", today); + Hawk.put("home_hot", netJson); + mActivity.runOnUiThread(() -> adapter.setNewInstance(loadHots(netJson))); + } - @Override - public String convertResponse(okhttp3.Response response) throws Throwable { - return response.body().string(); - } - }); + @Override + public String convertResponse(okhttp3.Response response) throws Throwable { + return response.body().string(); + } + }); + } else if (source == 1) { + if (homeSourceRec != null) adapter.setNewInstance(homeSourceRec); + } } catch (Throwable th) { th.printStackTrace(); } diff --git a/app/src/main/java/com/github/tvbox/osc/ui/tv/widget/SearchKeyboard.java b/app/src/main/java/com/github/tvbox/osc/ui/tv/widget/SearchKeyboard.java index 997a9e1..7f8458b 100644 --- a/app/src/main/java/com/github/tvbox/osc/ui/tv/widget/SearchKeyboard.java +++ b/app/src/main/java/com/github/tvbox/osc/ui/tv/widget/SearchKeyboard.java @@ -13,7 +13,6 @@ import androidx.recyclerview.widget.RecyclerView; import com.chad.library.adapter.base.BaseMultiItemQuickAdapter; -import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.entity.MultiItemEntity; import com.chad.library.adapter.base.viewholder.BaseViewHolder; import com.github.tvbox.osc.R; @@ -60,6 +59,14 @@ private void initView() { View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_keyborad, this); mRecyclerView = (RecyclerView) view.findViewById(R.id.mRecyclerView); GridLayoutManager manager = new GridLayoutManager(getContext(), 6); + manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { + @Override + public int getSpanSize(int position) { + if (position == 0) return 3; + else if (position == 1) return 3; + return 1; + } + }); mRecyclerView.setLayoutManager(manager); mRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() { @Override @@ -80,15 +87,6 @@ public void onChildViewDetachedFromWindow(@NonNull View view) { } final KeyboardAdapter adapter = new KeyboardAdapter(keyboardList); mRecyclerView.setAdapter(adapter); - //TODO 寻找替代方法 -// adapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() { -// @Override -// public int getSpanSize(GridLayoutManager gridLayoutManager, int position) { -// if (position == 0) return 3; -// else if (position == 1) return 3; -// return 1; -// } -// }); adapter.setOnItemClickListener((adapter1, view1, position) -> { Keyboard keyboard = (Keyboard) adapter1.getItem(position); if (searchKeyListener != null) { diff --git a/app/src/main/java/com/github/tvbox/osc/util/js/JSEngine.java b/app/src/main/java/com/github/tvbox/osc/util/js/JSEngine.java index eed5d23..7f981cd 100644 --- a/app/src/main/java/com/github/tvbox/osc/util/js/JSEngine.java +++ b/app/src/main/java/com/github/tvbox/osc/util/js/JSEngine.java @@ -10,7 +10,6 @@ import com.github.tvbox.osc.base.App; import com.github.tvbox.osc.util.OkGoHelper; import com.github.tvbox.quickjs.JSArray; -import com.github.tvbox.quickjs.JSCallFunction; import com.github.tvbox.quickjs.JSModule; import com.github.tvbox.quickjs.JSObject; import com.github.tvbox.quickjs.QuickJSContext; @@ -21,7 +20,6 @@ import java.io.InputStream; import java.net.URL; -import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -40,8 +38,7 @@ public class JSEngine { static JSEngine instance = null; public static JSEngine getInstance() { - if (instance == null) - instance = new JSEngine(); + if (instance == null) instance = new JSEngine(); return instance; } @@ -133,16 +130,12 @@ public void postVoid(Event event, boolean block) throws Throwable { if (block) { synchronized (result) { try { - if (result[1] == null) { - result.wait(); - } + if (result[1] == null) result.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } - if (errors[0] != null) { - throw errors[0]; - } + if (errors[0] != null) throw errors[0]; } } @@ -155,202 +148,172 @@ public void init() { void initConsole() { jsContext.evaluate("var console = {};"); JSObject console = (JSObject) jsContext.getGlobalObject().getProperty("console"); - console.setProperty("log", new JSCallFunction() { - @Override - public Object call(Object... args) { - StringBuilder b = new StringBuilder(); - for (Object o : args) { - b.append(o == null ? "null" : o.toString()); - } - System.out.println(TAG + " >>> " + b); - return null; + console.setProperty("log", args -> { + StringBuilder b = new StringBuilder(); + for (Object o : args) { + b.append(o == null ? "null" : o.toString()); } + System.out.println(TAG + " >>> " + b); + return null; }); } void initLocalStorage() { jsContext.evaluate("var local = {};"); JSObject console = (JSObject) jsContext.getGlobalObject().getProperty("local"); - console.setProperty("get", new JSCallFunction() { - @Override - public Object call(Object... args) { - SharedPreferences sharedPreferences = App.getInstance().getSharedPreferences("js_engine_" + args[0].toString(), Context.MODE_PRIVATE); - return sharedPreferences.getString(args[1].toString(), ""); - } + console.setProperty("get", args -> { + SharedPreferences sharedPreferences = App.getInstance().getSharedPreferences("js_engine_" + args[0].toString(), Context.MODE_PRIVATE); + return sharedPreferences.getString(args[1].toString(), ""); }); - console.setProperty("set", new JSCallFunction() { - @Override - public Object call(Object... args) { - SharedPreferences sharedPreferences = App.getInstance().getSharedPreferences("js_engine_" + args[0].toString(), Context.MODE_PRIVATE); - sharedPreferences.edit().putString(args[1].toString(), args[2].toString()).commit(); - return null; - } + console.setProperty("set", args -> { + SharedPreferences sharedPreferences = App.getInstance().getSharedPreferences("js_engine_" + args[0].toString(), Context.MODE_PRIVATE); + sharedPreferences.edit().putString(args[1].toString(), args[2].toString()).commit(); + return null; }); - console.setProperty("delete", new JSCallFunction() { - @Override - public Object call(Object... args) { - SharedPreferences sharedPreferences = App.getInstance().getSharedPreferences("js_engine_" + args[0].toString(), Context.MODE_PRIVATE); - sharedPreferences.edit().remove(args[1].toString()).commit(); - return null; - } + console.setProperty("delete", args -> { + SharedPreferences sharedPreferences = App.getInstance().getSharedPreferences("js_engine_" + args[0].toString(), Context.MODE_PRIVATE); + sharedPreferences.edit().remove(args[1].toString()).commit(); + return null; }); } void initOkHttp() { - jsContext.getGlobalObject().setProperty("req", new JSCallFunction() { - @Override - public Object call(Object... args) { - try { - String url = args[0].toString(); - JSONObject opt = new JSONObject(jsContext.stringify((JSObject) args[1])); - Headers.Builder headerBuilder = new Headers.Builder(); - JSONObject optHeader = opt.optJSONObject("headers"); - if (optHeader != null) { - Iterator hdKeys = optHeader.keys(); - while (hdKeys.hasNext()) { - String k = hdKeys.next(); - String v = optHeader.optString(k); - headerBuilder.add(k, v); - } + jsContext.getGlobalObject().setProperty("req", args -> { + try { + String url = args[0].toString(); + JSONObject opt = new JSONObject(jsContext.stringify((JSObject) args[1])); + Headers.Builder headerBuilder = new Headers.Builder(); + JSONObject optHeader = opt.optJSONObject("headers"); + if (optHeader != null) { + Iterator hdKeys = optHeader.keys(); + while (hdKeys.hasNext()) { + String k = hdKeys.next(); + String v = optHeader.optString(k); + headerBuilder.add(k, v); } - Headers headers = headerBuilder.build(); - String method = opt.optString("method", "get"); - Request.Builder requestBuilder = new Request.Builder().url(url).headers(headers).tag("js_okhttp_tag"); - Request request = null; - if (method.equalsIgnoreCase("post")) { - RequestBody body = null; - String data = opt.optString("data", "").trim(); - if (!data.isEmpty()) { - body = RequestBody.create(MediaType.parse("application/json"), data); - } - if (body == null) { - String dataBody = opt.optString("body", "").trim(); - if (!dataBody.isEmpty() && headers.get("Content-Type") != null) { - body = RequestBody.create(MediaType.parse(headers.get("Content-Type")), opt.optString("body", "")); - } - } - if (body == null) { - body = RequestBody.create(null, ""); - } - request = requestBuilder.post(body).build(); - } else if (method.equalsIgnoreCase("header")) { - request = requestBuilder.head().build(); - } else { - request = requestBuilder.get().build(); + } + Headers headers = headerBuilder.build(); + String method = opt.optString("method", "get"); + Request.Builder requestBuilder = new Request.Builder().url(url).headers(headers).tag("js_okhttp_tag"); + Request request = null; + if (method.equalsIgnoreCase("post")) { + RequestBody body = null; + String data = opt.optString("data", "").trim(); + if (!data.isEmpty()) { + body = RequestBody.create(MediaType.parse("application/json"), data); } - int redirect = opt.optInt("redirect", 1); - OkHttpClient client = null; - if (redirect == 1) { - client = OkGoHelper.getDefaultClient(); - } else { - client = OkGoHelper.getNoRedirectClient(); + if (body == null) { + String dataBody = opt.optString("body", "").trim(); + if (!dataBody.isEmpty() && headers.get("Content-Type") != null) { + body = RequestBody.create(MediaType.parse(headers.get("Content-Type")), opt.optString("body", "")); + } } - OkHttpClient.Builder clientBuilder = client.newBuilder(); - int timeout = 10000; - if (opt.has("timeout")) { - timeout = opt.optInt("timeout"); + if (body == null) { + body = RequestBody.create(null, ""); } - clientBuilder.readTimeout(timeout, TimeUnit.MILLISECONDS); - clientBuilder.writeTimeout(timeout, TimeUnit.MILLISECONDS); - clientBuilder.connectTimeout(timeout, TimeUnit.MILLISECONDS); - Response response = clientBuilder.build().newCall(request).execute(); + request = requestBuilder.post(body).build(); + } else if (method.equalsIgnoreCase("header")) { + request = requestBuilder.head().build(); + } else { + request = requestBuilder.get().build(); + } + int redirect = opt.optInt("redirect", 1); + OkHttpClient client = null; + if (redirect == 1) { + client = OkGoHelper.getDefaultClient(); + } else { + client = OkGoHelper.getNoRedirectClient(); + } + OkHttpClient.Builder clientBuilder = client.newBuilder(); + int timeout = 10000; + if (opt.has("timeout")) { + timeout = opt.optInt("timeout"); + } + clientBuilder.readTimeout(timeout, TimeUnit.MILLISECONDS); + clientBuilder.writeTimeout(timeout, TimeUnit.MILLISECONDS); + clientBuilder.connectTimeout(timeout, TimeUnit.MILLISECONDS); + Response response = clientBuilder.build().newCall(request).execute(); - JSObject jsObject = jsContext.createNewJSObject(); - Set resHeaders = response.headers().names(); - JSObject resHeader = jsContext.createNewJSObject(); - for (String header : resHeaders) { - resHeader.setProperty(header, response.header(header)); + JSObject jsObject = jsContext.createNewJSObject(); + Set resHeaders = response.headers().names(); + JSObject resHeader = jsContext.createNewJSObject(); + for (String header : resHeaders) { + resHeader.setProperty(header, response.header(header)); + } + jsObject.setProperty("headers", resHeader); + int returnBuffer = opt.optInt("buffer", 0); + if (returnBuffer == 1) { + JSArray array = jsContext.createNewJSArray(); + byte[] bytes = response.body().bytes(); + for (int i = 0; i < bytes.length; i++) { + array.set(bytes[i], i); } - jsObject.setProperty("headers", resHeader); - int returnBuffer = opt.optInt("buffer", 0); - if (returnBuffer == 1) { - JSArray array = jsContext.createNewJSArray(); - byte[] bytes = response.body().bytes(); - for (int i = 0; i < bytes.length; i++) { - array.set(bytes[i], i); - } - jsObject.setProperty("content", array); - } else if (returnBuffer == 2) { - jsObject.setProperty("content", Base64.encodeToString(response.body().bytes(), Base64.DEFAULT)); + jsObject.setProperty("content", array); + } else if (returnBuffer == 2) { + jsObject.setProperty("content", Base64.encodeToString(response.body().bytes(), Base64.DEFAULT)); + } else { + String res; + if (headers.get("Content-Type") != null && headers.get("Content-Type").contains("=")) { + byte[] responseBytes = UTF8BOMFighter.removeUTF8BOM(response.body().bytes()); + res = new String(responseBytes, headers.get("Content-Type").split("=")[1].trim()); } else { - String res; - if (headers.get("Content-Type") != null && headers.get("Content-Type").contains("=")) { - byte[] responseBytes = UTF8BOMFighter.removeUTF8BOM(response.body().bytes()); - res = new String(responseBytes, headers.get("Content-Type").split("=")[1].trim()); - } else { - res = response.body().string(); - } - jsObject.setProperty("content", res); + res = response.body().string(); } - return jsObject; - } catch (Throwable throwable) { - throwable.printStackTrace(); + jsObject.setProperty("content", res); } - JSObject jsObject = jsContext.createNewJSObject(); - JSObject resHeader = jsContext.createNewJSObject(); - jsObject.setProperty("headers", resHeader); - jsObject.setProperty("content", ""); return jsObject; + } catch (Throwable throwable) { + throwable.printStackTrace(); } + JSObject jsObject = jsContext.createNewJSObject(); + JSObject resHeader = jsContext.createNewJSObject(); + jsObject.setProperty("headers", resHeader); + jsObject.setProperty("content", ""); + return jsObject; }); - jsContext.getGlobalObject().setProperty("joinUrl", new JSCallFunction() { - @Override - public String call(Object... args) { - URL url; - String q = ""; - try { - String parent = args[0].toString(); - String child = args[1].toString(); - // TODO - if (parent.isEmpty()) { - return child; - } - url = new URL(new URL(parent), child); - q = url.toExternalForm(); - } catch (Throwable throwable) { - throwable.printStackTrace(); - } - return q; + jsContext.getGlobalObject().setProperty("joinUrl", args -> { + URL url; + String q = ""; + try { + String parent = args[0].toString(); + String child = args[1].toString(); + if (parent.isEmpty()) return child; + url = new URL(new URL(parent), child); + q = url.toExternalForm(); + } catch (Throwable throwable) { + throwable.printStackTrace(); } + return q; }); - jsContext.getGlobalObject().setProperty("pdfh", new JSCallFunction() { - @Override - public String call(Object... args) { - try { + jsContext.getGlobalObject().setProperty("pdfh", args -> { + try { // LOG.i("pdfh----------------:"+args[1].toString().trim()); - String html = args[0].toString(); - return HtmlParser.parseDomForUrl(html, args[1].toString().trim(), ""); - } catch (Throwable throwable) { - throwable.printStackTrace(); - } - return ""; + String html = args[0].toString(); + return HtmlParser.parseDomForUrl(html, args[1].toString().trim(), ""); + } catch (Throwable throwable) { + throwable.printStackTrace(); } + return ""; }); - jsContext.getGlobalObject().setProperty("pdfa", new JSCallFunction() { - @Override - public Object call(Object... args) { - try { + jsContext.getGlobalObject().setProperty("pdfa", args -> { + try { // LOG.i("pdfa----------------:"+args[1].toString().trim()); - String html = args[0].toString(); - return jsContext.parseJSON(new Gson().toJson(HtmlParser.parseDomForList(html, args[1].toString().trim()))); - } catch (Throwable throwable) { - throwable.printStackTrace(); - } - return null; + String html = args[0].toString(); + return jsContext.parseJSON(new Gson().toJson(HtmlParser.parseDomForList(html, args[1].toString().trim()))); + } catch (Throwable throwable) { + throwable.printStackTrace(); } + return null; }); - jsContext.getGlobalObject().setProperty("pd", new JSCallFunction() { - @Override - public String call(Object... args) { - try { + jsContext.getGlobalObject().setProperty("pd", args -> { + try { // LOG.i("pd----------------:"+args[2].toString().trim()); - String html = args[0].toString(); - return HtmlParser.parseDomForUrl(html, args[1].toString().trim(), args[2].toString()); - } catch (Throwable throwable) { - throwable.printStackTrace(); - } - return ""; + String html = args[0].toString(); + return HtmlParser.parseDomForUrl(html, args[1].toString().trim(), args[2].toString()); + } catch (Throwable throwable) { + throwable.printStackTrace(); } + return ""; }); } @@ -372,7 +335,7 @@ static String loadModule(String name) { InputStream is = App.getInstance().getAssets().open(name.substring(9)); byte[] data = new byte[is.available()]; is.read(data); - content = new String(data, StandardCharsets.UTF_8); + content = new String(data, "UTF-8"); } if (content != null && !content.isEmpty()) { moduleCache.put(name, content); @@ -421,12 +384,7 @@ public JSThread getJSThread() { } } QuickJSContext jsContext = (QuickJSContext) objects[0]; - JSModule.setModuleLoader(new JSModule.Loader() { - @Override - public String getModuleScript(String moduleName) { - return loadModule(moduleName); - } - }); + JSModule.setModuleLoader(moduleName -> loadModule(moduleName)); JSThread jsThread = new JSThread(); jsThread.handler = handler; jsThread.thread = handlerThread; @@ -453,12 +411,8 @@ public String getModuleScript(String moduleName) { public void destroy() { for (String name : threads.keySet()) { JSThread jsThread = threads.get(name); - if (jsThread != null && jsThread.thread != null) { - jsThread.thread.interrupt(); - } - if (jsThread.jsContext != null) { - jsThread.jsContext.destroyContext(); - } + if (jsThread != null && jsThread.thread != null) jsThread.thread.interrupt(); + if (jsThread.jsContext != null) jsThread.jsContext.destroyContext(); } threads.clear(); } @@ -467,9 +421,7 @@ public void stopAll() { OkGo.getInstance().cancelTag("js_okhttp_tag"); for (String name : threads.keySet()) { JSThread jsThread = threads.get(name); - if (jsThread.handler != null) { - jsThread.handler.removeCallbacksAndMessages(null); - } + if (jsThread.handler != null) jsThread.handler.removeCallbacksAndMessages(null); } } diff --git a/app/src/main/java/com/github/tvbox/osc/viewmodel/SourceViewModel.java b/app/src/main/java/com/github/tvbox/osc/viewmodel/SourceViewModel.java index d3bb1cd..77f250e 100644 --- a/app/src/main/java/com/github/tvbox/osc/viewmodel/SourceViewModel.java +++ b/app/src/main/java/com/github/tvbox/osc/viewmodel/SourceViewModel.java @@ -41,7 +41,6 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -110,12 +109,8 @@ public void getSort(String sourceKey) { sortResult.postValue(sortXml); }); } - } else { - sortResult.postValue(sortXml); - } - } else { - sortResult.postValue(null); - } + } else sortResult.postValue(sortXml); + } else sortResult.postValue(null); try { executor.shutdown(); } catch (Throwable th) { diff --git a/app/src/main/java/com/github/tvbox/osc/viewmodel/SubtitleViewModel.java b/app/src/main/java/com/github/tvbox/osc/viewmodel/SubtitleViewModel.java index 3b4d6da..7dc1c37 100644 --- a/app/src/main/java/com/github/tvbox/osc/viewmodel/SubtitleViewModel.java +++ b/app/src/main/java/com/github/tvbox/osc/viewmodel/SubtitleViewModel.java @@ -99,7 +99,7 @@ public void onSuccess(com.lzy.okgo.model.Response response) { if (pages.size() > 0) { String[] ps = pages.last().text().split("/", 2); if (ps.length == 2 && !TextUtils.isEmpty(ps[1])) { - pagesTotal = Integer.valueOf(ps[1].trim()); + pagesTotal = Integer.parseInt(ps[1].trim()); } } } catch (Throwable th) { diff --git a/app/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.java b/app/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.java index 4ff8d6b..7ebe904 100644 --- a/app/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.java +++ b/app/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.java @@ -124,8 +124,7 @@ public boolean resolvePublicAddresses() { @Override public List lookup(String hostname) throws UnknownHostException { - if (this.url == null) - return Dns.SYSTEM.lookup(hostname); + if (this.url == null) return Dns.SYSTEM.lookup(hostname); if (!resolvePrivateAddresses || !resolvePublicAddresses) { boolean privateHost = isPrivateHost(hostname); @@ -144,13 +143,11 @@ public byte[] lookupHttpsForwardSync(String hostname) throws Throwable { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { byteArrayOutputStream.write(executeRequestsSync(hostname, DnsRecordCodec.TYPE_A)); - } finally { - + } catch (Exception ignored) { } try { byteArrayOutputStream.write(executeRequestsSync(hostname, DnsRecordCodec.TYPE_AAAA)); - } finally { - + } catch (Exception ignored) { } return byteArrayOutputStream.toByteArray(); } @@ -159,46 +156,29 @@ private List lookupHttps(String hostname) throws UnknownHostExcepti List networkRequests = new ArrayList<>(2); List failures = new ArrayList<>(2); List results = new ArrayList<>(5); - buildRequest(hostname, networkRequests, results, failures, DnsRecordCodec.TYPE_A); - - if (includeIPv6) { + if (includeIPv6) buildRequest(hostname, networkRequests, results, failures, DnsRecordCodec.TYPE_AAAA); - } - executeRequests(hostname, networkRequests, results, failures); - - if (!results.isEmpty()) { - return results; - } + if (!results.isEmpty()) return results; return Dns.SYSTEM.lookup(hostname); - // return throwBestFailure(hostname, failures); } - private void buildRequest(String hostname, List networkRequests, List results, - List failures, int type) { + private void buildRequest(String hostname, List networkRequests, List results, List failures, int type) { Request request = buildRequest(hostname, type); Response response = getCacheOnlyResponse(request); - - if (response != null) { - processResponse(response, hostname, results, failures); - } else { - networkRequests.add(client.newCall(request)); - } + if (response != null) processResponse(response, hostname, results, failures); + else networkRequests.add(client.newCall(request)); } private byte[] executeRequestsSync(String hostname, int type) throws IOException { Request request = buildRequest(hostname, type); Response response = getCacheOnlyResponse(request); - - if (response == null) { - response = client.newCall(request).execute(); - } + if (response == null) response = client.newCall(request).execute(); return response.body().bytes(); } - private void executeRequests(final String hostname, List networkRequests, - final List responses, final List failures) { + private void executeRequests(final String hostname, List networkRequests, final List responses, final List failures) { final CountDownLatch latch = new CountDownLatch(networkRequests.size()); for (Call call : networkRequests) { @@ -226,8 +206,7 @@ public void onResponse(Call call, Response response) { } } - private void processResponse(Response response, String hostname, List results, - List failures) { + private void processResponse(Response response, String hostname, List results, List failures) { try { List addresses = readResponse(hostname, response); synchronized (results) { @@ -240,40 +219,24 @@ private void processResponse(Response response, String hostname, List throwBestFailure(String hostname, List failures) - throws UnknownHostException { - if (failures.size() == 0) { - throw new UnknownHostException(hostname); - } - + private List throwBestFailure(String hostname, List failures) throws UnknownHostException { + if (failures.size() == 0) throw new UnknownHostException(hostname); Exception failure = failures.get(0); - - if (failure instanceof UnknownHostException) { - throw (UnknownHostException) failure; - } - + if (failure instanceof UnknownHostException) throw (UnknownHostException) failure; UnknownHostException unknownHostException = new UnknownHostException(hostname); unknownHostException.initCause(failure); throw unknownHostException; } - private @Nullable - Response getCacheOnlyResponse(Request request) { + private @Nullable Response getCacheOnlyResponse(Request request) { if (!post && client.cache() != null) { try { Request cacheRequest = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build(); - Response cacheResponse = client.newCall(cacheRequest).execute(); - - if (cacheResponse.code() != 504) { - return cacheResponse; - } - } catch (IOException ioe) { - // Failures are ignored as we can fallback to the network - // and hopefully repopulate the cache. + if (cacheResponse.code() != 504) return cacheResponse; + } catch (IOException ignored) { } } - return null; } @@ -283,22 +246,14 @@ private List readResponse(String hostname, Response response) throw } try { - if (!response.isSuccessful()) { + if (!response.isSuccessful()) throw new IOException("response: " + response.code() + " " + response.message()); - } - ResponseBody body = response.body(); - if (body.contentLength() > MAX_RESPONSE_SIZE) { - throw new IOException("response size exceeds limit (" - + MAX_RESPONSE_SIZE - + " bytes): " - + body.contentLength() - + " bytes"); + throw new IOException("response size exceeds limit (" + MAX_RESPONSE_SIZE + " bytes): " + body.contentLength() + " bytes"); } ByteString responseBytes = body.source().readByteString(); - return DnsRecordCodec.decodeAnswers(hostname, responseBytes); } finally { response.close(); @@ -307,18 +262,14 @@ private List readResponse(String hostname, Response response) throw private Request buildRequest(String hostname, int type) { Request.Builder requestBuilder = new Request.Builder().header("Accept", DNS_MESSAGE.toString()); - ByteString query = DnsRecordCodec.encodeQuery(hostname, type); - if (post) { requestBuilder = requestBuilder.url(url).post(RequestBody.create(DNS_MESSAGE, query)); } else { String encoded = query.base64Url().replace("=", ""); HttpUrl requestUrl = url.newBuilder().addQueryParameter("dns", encoded).build(); - requestBuilder = requestBuilder.url(requestUrl); } - return requestBuilder.build(); } diff --git a/app/src/main/res/layout/activity_home.xml b/app/src/main/res/layout/activity_home.xml index 83f378a..edd69b5 100644 --- a/app/src/main/res/layout/activity_home.xml +++ b/app/src/main/res/layout/activity_home.xml @@ -1,7 +1,6 @@ @@ -97,21 +96,22 @@ android:nextFocusDown="@id/tvDrive" android:src="@drawable/hm_settings" /> - - + android:textStyle="bold" />