mirror of
https://github.com/revanced/revanced-patches
synced 2024-12-29 12:25:49 +01:00
chore: Merge integrations
This commit is contained in:
parent
eee1692277
commit
a361bfb1da
@ -0,0 +1,11 @@
|
|||||||
|
extension {
|
||||||
|
name = "extensions/all/screencapture/remove-screen-capture-restriction.rve"
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "app.revanced.extension"
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
compileOnly(libs.annotation)
|
||||||
|
}
|
@ -0,0 +1 @@
|
|||||||
|
<manifest/>
|
@ -0,0 +1,21 @@
|
|||||||
|
package app.revanced.extension.all.screencapture.removerestriction;
|
||||||
|
|
||||||
|
import android.media.AudioAttributes;
|
||||||
|
import android.os.Build;
|
||||||
|
|
||||||
|
import androidx.annotation.RequiresApi;
|
||||||
|
|
||||||
|
public final class RemoveScreencaptureRestrictionPatch {
|
||||||
|
// Member of AudioAttributes.Builder
|
||||||
|
@RequiresApi(api = Build.VERSION_CODES.Q)
|
||||||
|
public static AudioAttributes.Builder setAllowedCapturePolicy(final AudioAttributes.Builder builder, final int capturePolicy) {
|
||||||
|
builder.setAllowedCapturePolicy(AudioAttributes.ALLOW_CAPTURE_BY_ALL);
|
||||||
|
|
||||||
|
return builder;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Member of AudioManager static class
|
||||||
|
public static void setAllowedCapturePolicy(final int capturePolicy) {
|
||||||
|
// Ignore request
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,7 @@
|
|||||||
|
extension {
|
||||||
|
name = "extensions/all/screenshot/remove-screenshot-restriction.rve"
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "app.revanced.extension"
|
||||||
|
}
|
@ -0,0 +1 @@
|
|||||||
|
<manifest/>
|
@ -0,0 +1,15 @@
|
|||||||
|
package app.revanced.extension.all.screenshot.removerestriction;
|
||||||
|
|
||||||
|
import android.view.Window;
|
||||||
|
import android.view.WindowManager;
|
||||||
|
|
||||||
|
public class RemoveScreenshotRestrictionPatch {
|
||||||
|
|
||||||
|
public static void addFlags(Window window, int flags) {
|
||||||
|
window.addFlags(flags & ~WindowManager.LayoutParams.FLAG_SECURE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void setFlags(Window window, int flags, int mask) {
|
||||||
|
window.setFlags(flags & ~WindowManager.LayoutParams.FLAG_SECURE, mask & ~WindowManager.LayoutParams.FLAG_SECURE);
|
||||||
|
}
|
||||||
|
}
|
22
extensions/shared/build.gradle.kts
Normal file
22
extensions/shared/build.gradle.kts
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
extension {
|
||||||
|
name = "extensions/shared.rve"
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "app.revanced.extension"
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
isMinifyEnabled = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
compileOnly(libs.appcompat)
|
||||||
|
compileOnly(libs.annotation)
|
||||||
|
compileOnly(libs.okhttp)
|
||||||
|
compileOnly(libs.retrofit)
|
||||||
|
|
||||||
|
compileOnly(project(":extensions:shared:stub"))
|
||||||
|
}
|
9
extensions/shared/proguard-rules.pro
vendored
Normal file
9
extensions/shared/proguard-rules.pro
vendored
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
-dontobfuscate
|
||||||
|
-dontoptimize
|
||||||
|
-keepattributes *
|
||||||
|
-keep class app.revanced.** {
|
||||||
|
*;
|
||||||
|
}
|
||||||
|
-keep class com.google.** {
|
||||||
|
*;
|
||||||
|
}
|
4
extensions/shared/src/main/AndroidManifest.xml
Normal file
4
extensions/shared/src/main/AndroidManifest.xml
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
|
||||||
|
</manifest>
|
@ -0,0 +1,24 @@
|
|||||||
|
package app.revanced.extension.boostforreddit;
|
||||||
|
|
||||||
|
import com.rubenmayayo.reddit.ui.activities.WebViewActivity;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.fixes.slink.BaseFixSLinksPatch;
|
||||||
|
|
||||||
|
/** @noinspection unused*/
|
||||||
|
public class FixSLinksPatch extends BaseFixSLinksPatch {
|
||||||
|
static {
|
||||||
|
INSTANCE = new FixSLinksPatch();
|
||||||
|
}
|
||||||
|
|
||||||
|
private FixSLinksPatch() {
|
||||||
|
webViewActivityClass = WebViewActivity.class;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean patchResolveSLink(String link) {
|
||||||
|
return INSTANCE.resolveSLink(link);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void patchSetAccessToken(String accessToken) {
|
||||||
|
INSTANCE.setAccessToken(accessToken);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package app.revanced.extension.reddit.patches;
|
||||||
|
|
||||||
|
import com.reddit.domain.model.ILink;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public final class FilterPromotedLinksPatch {
|
||||||
|
/**
|
||||||
|
* Filters list from promoted links.
|
||||||
|
**/
|
||||||
|
public static List<?> filterChildren(final Iterable<?> links) {
|
||||||
|
final List<Object> filteredList = new ArrayList<>();
|
||||||
|
|
||||||
|
for (Object item : links) {
|
||||||
|
if (item instanceof ILink && ((ILink) item).getPromoted()) continue;
|
||||||
|
|
||||||
|
filteredList.add(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
return filteredList;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,158 @@
|
|||||||
|
package app.revanced.extension.shared;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint;
|
||||||
|
import android.app.Activity;
|
||||||
|
import android.app.AlertDialog;
|
||||||
|
import android.app.SearchManager;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.DialogInterface;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.content.pm.PackageManager;
|
||||||
|
import android.net.Uri;
|
||||||
|
import android.os.Build;
|
||||||
|
import android.os.PowerManager;
|
||||||
|
import android.provider.Settings;
|
||||||
|
|
||||||
|
import androidx.annotation.RequiresApi;
|
||||||
|
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @noinspection unused
|
||||||
|
*/
|
||||||
|
public class GmsCoreSupport {
|
||||||
|
public static final String ORIGINAL_UNPATCHED_PACKAGE_NAME = "com.google.android.youtube";
|
||||||
|
private static final String GMS_CORE_PACKAGE_NAME
|
||||||
|
= getGmsCoreVendorGroupId() + ".android.gms";
|
||||||
|
private static final Uri GMS_CORE_PROVIDER
|
||||||
|
= Uri.parse("content://" + getGmsCoreVendorGroupId() + ".android.gsf.gservices/prefix");
|
||||||
|
private static final String DONT_KILL_MY_APP_LINK
|
||||||
|
= "https://dontkillmyapp.com";
|
||||||
|
|
||||||
|
private static void open(String queryOrLink) {
|
||||||
|
Intent intent;
|
||||||
|
try {
|
||||||
|
// Check if queryOrLink is a valid URL.
|
||||||
|
new URL(queryOrLink);
|
||||||
|
|
||||||
|
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(queryOrLink));
|
||||||
|
} catch (MalformedURLException e) {
|
||||||
|
intent = new Intent(Intent.ACTION_WEB_SEARCH);
|
||||||
|
intent.putExtra(SearchManager.QUERY, queryOrLink);
|
||||||
|
}
|
||||||
|
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||||
|
Utils.getContext().startActivity(intent);
|
||||||
|
|
||||||
|
// Gracefully exit, otherwise the broken app will continue to run.
|
||||||
|
System.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void showBatteryOptimizationDialog(Activity context,
|
||||||
|
String dialogMessageRef,
|
||||||
|
String positiveButtonStringRef,
|
||||||
|
DialogInterface.OnClickListener onPositiveClickListener) {
|
||||||
|
// Do not set cancelable to false, to allow using back button to skip the action,
|
||||||
|
// just in case the check can never be satisfied.
|
||||||
|
var dialog = new AlertDialog.Builder(context)
|
||||||
|
.setIconAttribute(android.R.attr.alertDialogIcon)
|
||||||
|
.setTitle(str("gms_core_dialog_title"))
|
||||||
|
.setMessage(str(dialogMessageRef))
|
||||||
|
.setPositiveButton(str(positiveButtonStringRef), onPositiveClickListener)
|
||||||
|
.create();
|
||||||
|
Utils.showDialog(context, dialog);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injection point.
|
||||||
|
*/
|
||||||
|
@RequiresApi(api = Build.VERSION_CODES.N)
|
||||||
|
public static void checkGmsCore(Activity context) {
|
||||||
|
try {
|
||||||
|
// Verify the user has not included GmsCore for a root installation.
|
||||||
|
// GmsCore Support changes the package name, but with a mounted installation
|
||||||
|
// all manifest changes are ignored and the original package name is used.
|
||||||
|
if (context.getPackageName().equals(ORIGINAL_UNPATCHED_PACKAGE_NAME)) {
|
||||||
|
Logger.printInfo(() -> "App is mounted with root, but GmsCore patch was included");
|
||||||
|
// Cannot use localize text here, since the app will load
|
||||||
|
// resources from the unpatched app and all patch strings are missing.
|
||||||
|
Utils.showToastLong("The 'GmsCore support' patch breaks mount installations");
|
||||||
|
|
||||||
|
// Do not exit. If the app exits before launch completes (and without
|
||||||
|
// opening another activity), then on some devices such as Pixel phone Android 10
|
||||||
|
// no toast will be shown and the app will continually be relaunched
|
||||||
|
// with the appearance of a hung app.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify GmsCore is installed.
|
||||||
|
try {
|
||||||
|
PackageManager manager = context.getPackageManager();
|
||||||
|
manager.getPackageInfo(GMS_CORE_PACKAGE_NAME, PackageManager.GET_ACTIVITIES);
|
||||||
|
} catch (PackageManager.NameNotFoundException exception) {
|
||||||
|
Logger.printInfo(() -> "GmsCore was not found");
|
||||||
|
// Cannot show a dialog and must show a toast,
|
||||||
|
// because on some installations the app crashes before a dialog can be displayed.
|
||||||
|
Utils.showToastLong(str("gms_core_toast_not_installed_message"));
|
||||||
|
open(getGmsCoreDownload());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if GmsCore is running in the background.
|
||||||
|
try (var client = context.getContentResolver().acquireContentProviderClient(GMS_CORE_PROVIDER)) {
|
||||||
|
if (client == null) {
|
||||||
|
Logger.printInfo(() -> "GmsCore is not running in the background");
|
||||||
|
|
||||||
|
showBatteryOptimizationDialog(context,
|
||||||
|
"gms_core_dialog_not_whitelisted_not_allowed_in_background_message",
|
||||||
|
"gms_core_dialog_open_website_text",
|
||||||
|
(dialog, id) -> open(DONT_KILL_MY_APP_LINK));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if GmsCore is whitelisted from battery optimizations.
|
||||||
|
if (batteryOptimizationsEnabled(context)) {
|
||||||
|
Logger.printInfo(() -> "GmsCore is not whitelisted from battery optimizations");
|
||||||
|
showBatteryOptimizationDialog(context,
|
||||||
|
"gms_core_dialog_not_whitelisted_using_battery_optimizations_message",
|
||||||
|
"gms_core_dialog_continue_text",
|
||||||
|
(dialog, id) -> openGmsCoreDisableBatteryOptimizationsIntent(context));
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "checkGmsCore failure", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("BatteryLife") // Permission is part of GmsCore
|
||||||
|
private static void openGmsCoreDisableBatteryOptimizationsIntent(Activity activity) {
|
||||||
|
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
|
||||||
|
intent.setData(Uri.fromParts("package", GMS_CORE_PACKAGE_NAME, null));
|
||||||
|
activity.startActivityForResult(intent, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return If GmsCore is not whitelisted from battery optimizations.
|
||||||
|
*/
|
||||||
|
private static boolean batteryOptimizationsEnabled(Context context) {
|
||||||
|
var powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
|
||||||
|
return !powerManager.isIgnoringBatteryOptimizations(GMS_CORE_PACKAGE_NAME);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String getGmsCoreDownload() {
|
||||||
|
final var vendorGroupId = getGmsCoreVendorGroupId();
|
||||||
|
//noinspection SwitchStatementWithTooFewBranches
|
||||||
|
switch (vendorGroupId) {
|
||||||
|
case "app.revanced":
|
||||||
|
return "https://github.com/revanced/gmscore/releases/latest";
|
||||||
|
default:
|
||||||
|
return vendorGroupId + ".android.gms";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Modified by a patch. Do not touch.
|
||||||
|
private static String getGmsCoreVendorGroupId() {
|
||||||
|
return "app.revanced";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,168 @@
|
|||||||
|
package app.revanced.extension.shared;
|
||||||
|
|
||||||
|
import android.util.Log;
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
import app.revanced.extension.shared.settings.BaseSettings;
|
||||||
|
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.settings.BaseSettings.*;
|
||||||
|
|
||||||
|
public class Logger {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log messages using lambdas.
|
||||||
|
*/
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface LogMessage {
|
||||||
|
@NonNull
|
||||||
|
String buildMessageString();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return For outer classes, this returns {@link Class#getSimpleName()}.
|
||||||
|
* For static, inner, or anonymous classes, this returns the simple name of the enclosing class.
|
||||||
|
* <br>
|
||||||
|
* For example, each of these classes return 'SomethingView':
|
||||||
|
* <code>
|
||||||
|
* com.company.SomethingView
|
||||||
|
* com.company.SomethingView$StaticClass
|
||||||
|
* com.company.SomethingView$1
|
||||||
|
* </code>
|
||||||
|
*/
|
||||||
|
private String findOuterClassSimpleName() {
|
||||||
|
var selfClass = this.getClass();
|
||||||
|
|
||||||
|
String fullClassName = selfClass.getName();
|
||||||
|
final int dollarSignIndex = fullClassName.indexOf('$');
|
||||||
|
if (dollarSignIndex < 0) {
|
||||||
|
return selfClass.getSimpleName(); // Already an outer class.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Class is inner, static, or anonymous.
|
||||||
|
// Parse the simple name full name.
|
||||||
|
// A class with no package returns index of -1, but incrementing gives index zero which is correct.
|
||||||
|
final int simpleClassNameStartIndex = fullClassName.lastIndexOf('.') + 1;
|
||||||
|
return fullClassName.substring(simpleClassNameStartIndex, dollarSignIndex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final String REVANCED_LOG_PREFIX = "revanced: ";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs debug messages under the outer class name of the code calling this method.
|
||||||
|
* Whenever possible, the log string should be constructed entirely inside {@link LogMessage#buildMessageString()}
|
||||||
|
* so the performance cost of building strings is paid only if {@link BaseSettings#DEBUG} is enabled.
|
||||||
|
*/
|
||||||
|
public static void printDebug(@NonNull LogMessage message) {
|
||||||
|
printDebug(message, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs debug messages under the outer class name of the code calling this method.
|
||||||
|
* Whenever possible, the log string should be constructed entirely inside {@link LogMessage#buildMessageString()}
|
||||||
|
* so the performance cost of building strings is paid only if {@link BaseSettings#DEBUG} is enabled.
|
||||||
|
*/
|
||||||
|
public static void printDebug(@NonNull LogMessage message, @Nullable Exception ex) {
|
||||||
|
if (DEBUG.get()) {
|
||||||
|
String logMessage = message.buildMessageString();
|
||||||
|
String logTag = REVANCED_LOG_PREFIX + message.findOuterClassSimpleName();
|
||||||
|
|
||||||
|
if (DEBUG_STACKTRACE.get()) {
|
||||||
|
var builder = new StringBuilder(logMessage);
|
||||||
|
var sw = new StringWriter();
|
||||||
|
new Throwable().printStackTrace(new PrintWriter(sw));
|
||||||
|
|
||||||
|
builder.append('\n').append(sw);
|
||||||
|
logMessage = builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ex == null) {
|
||||||
|
Log.d(logTag, logMessage);
|
||||||
|
} else {
|
||||||
|
Log.d(logTag, logMessage, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs information messages using the outer class name of the code calling this method.
|
||||||
|
*/
|
||||||
|
public static void printInfo(@NonNull LogMessage message) {
|
||||||
|
printInfo(message, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs information messages using the outer class name of the code calling this method.
|
||||||
|
*/
|
||||||
|
public static void printInfo(@NonNull LogMessage message, @Nullable Exception ex) {
|
||||||
|
String logTag = REVANCED_LOG_PREFIX + message.findOuterClassSimpleName();
|
||||||
|
String logMessage = message.buildMessageString();
|
||||||
|
if (ex == null) {
|
||||||
|
Log.i(logTag, logMessage);
|
||||||
|
} else {
|
||||||
|
Log.i(logTag, logMessage, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs exceptions under the outer class name of the code calling this method.
|
||||||
|
*/
|
||||||
|
public static void printException(@NonNull LogMessage message) {
|
||||||
|
printException(message, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs exceptions under the outer class name of the code calling this method.
|
||||||
|
*/
|
||||||
|
public static void printException(@NonNull LogMessage message, @Nullable Throwable ex) {
|
||||||
|
printException(message, ex, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs exceptions under the outer class name of the code calling this method.
|
||||||
|
* <p>
|
||||||
|
* If the calling code is showing it's own error toast,
|
||||||
|
* instead use {@link #printInfo(LogMessage, Exception)}
|
||||||
|
*
|
||||||
|
* @param message log message
|
||||||
|
* @param ex exception (optional)
|
||||||
|
* @param userToastMessage user specific toast message to show instead of the log message (optional)
|
||||||
|
*/
|
||||||
|
public static void printException(@NonNull LogMessage message, @Nullable Throwable ex,
|
||||||
|
@Nullable String userToastMessage) {
|
||||||
|
String messageString = message.buildMessageString();
|
||||||
|
String outerClassSimpleName = message.findOuterClassSimpleName();
|
||||||
|
String logMessage = REVANCED_LOG_PREFIX + outerClassSimpleName;
|
||||||
|
if (ex == null) {
|
||||||
|
Log.e(logMessage, messageString);
|
||||||
|
} else {
|
||||||
|
Log.e(logMessage, messageString, ex);
|
||||||
|
}
|
||||||
|
if (DEBUG_TOAST_ON_ERROR.get()) {
|
||||||
|
String toastMessageToDisplay = (userToastMessage != null)
|
||||||
|
? userToastMessage
|
||||||
|
: outerClassSimpleName + ": " + messageString;
|
||||||
|
Utils.showToastLong(toastMessageToDisplay);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logging to use if {@link BaseSettings#DEBUG} or {@link Utils#getContext()} may not be initialized.
|
||||||
|
* Normally this method should not be used.
|
||||||
|
*/
|
||||||
|
public static void initializationInfo(@NonNull Class<?> callingClass, @NonNull String message) {
|
||||||
|
Log.i(REVANCED_LOG_PREFIX + callingClass.getSimpleName(), message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logging to use if {@link BaseSettings#DEBUG} or {@link Utils#getContext()} may not be initialized.
|
||||||
|
* Normally this method should not be used.
|
||||||
|
*/
|
||||||
|
public static void initializationException(@NonNull Class<?> callingClass, @NonNull String message,
|
||||||
|
@Nullable Exception ex) {
|
||||||
|
Log.e(REVANCED_LOG_PREFIX + callingClass.getSimpleName(), message, ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,122 @@
|
|||||||
|
package app.revanced.extension.shared;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.res.Resources;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class StringRef {
|
||||||
|
private static Resources resources;
|
||||||
|
private static String packageName;
|
||||||
|
|
||||||
|
// must use a thread safe map, as this class is used both on and off the main thread
|
||||||
|
private static final Map<String, StringRef> strings = Collections.synchronizedMap(new HashMap<>());
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a cached instance.
|
||||||
|
* Should be used if the same String could be loaded more than once.
|
||||||
|
*
|
||||||
|
* @param id string resource name/id
|
||||||
|
* @see #sf(String)
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public static StringRef sfc(@NonNull String id) {
|
||||||
|
StringRef ref = strings.get(id);
|
||||||
|
if (ref == null) {
|
||||||
|
ref = new StringRef(id);
|
||||||
|
strings.put(id, ref);
|
||||||
|
}
|
||||||
|
return ref;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new instance, but does not cache the value.
|
||||||
|
* Should be used for Strings that are loaded exactly once.
|
||||||
|
*
|
||||||
|
* @param id string resource name/id
|
||||||
|
* @see #sfc(String)
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public static StringRef sf(@NonNull String id) {
|
||||||
|
return new StringRef(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets string value by string id, shorthand for <code>sfc(id).toString()</code>
|
||||||
|
*
|
||||||
|
* @param id string resource name/id
|
||||||
|
* @return String value from string.xml
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public static String str(@NonNull String id) {
|
||||||
|
return sfc(id).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets string value by string id, shorthand for <code>sfc(id).toString()</code> and formats the string
|
||||||
|
* with given args.
|
||||||
|
*
|
||||||
|
* @param id string resource name/id
|
||||||
|
* @param args the args to format the string with
|
||||||
|
* @return String value from string.xml formatted with given args
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public static String str(@NonNull String id, Object... args) {
|
||||||
|
return String.format(str(id), args);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a StringRef object that'll not change it's value
|
||||||
|
*
|
||||||
|
* @param value value which toString() method returns when invoked on returned object
|
||||||
|
* @return Unique StringRef instance, its value will never change
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public static StringRef constant(@NonNull String value) {
|
||||||
|
final StringRef ref = new StringRef(value);
|
||||||
|
ref.resolved = true;
|
||||||
|
return ref;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shorthand for <code>constant("")</code>
|
||||||
|
* Its value always resolves to empty string
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public static final StringRef empty = constant("");
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
private String value;
|
||||||
|
private boolean resolved;
|
||||||
|
|
||||||
|
public StringRef(@NonNull String resName) {
|
||||||
|
this.value = resName;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@NonNull
|
||||||
|
public String toString() {
|
||||||
|
if (!resolved) {
|
||||||
|
if (resources == null || packageName == null) {
|
||||||
|
Context context = Utils.getContext();
|
||||||
|
resources = context.getResources();
|
||||||
|
packageName = context.getPackageName();
|
||||||
|
}
|
||||||
|
resolved = true;
|
||||||
|
if (resources != null) {
|
||||||
|
final int identifier = resources.getIdentifier(value, "string", packageName);
|
||||||
|
if (identifier == 0)
|
||||||
|
Logger.printException(() -> "Resource not found: " + value);
|
||||||
|
else
|
||||||
|
value = resources.getString(identifier);
|
||||||
|
} else {
|
||||||
|
Logger.printException(() -> "Could not resolve resources!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,741 @@
|
|||||||
|
package app.revanced.extension.shared;
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint;
|
||||||
|
import android.app.*;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.content.pm.PackageInfo;
|
||||||
|
import android.content.pm.PackageManager;
|
||||||
|
import android.content.res.Resources;
|
||||||
|
import android.net.ConnectivityManager;
|
||||||
|
import android.os.Build;
|
||||||
|
import android.os.Bundle;
|
||||||
|
import android.os.Handler;
|
||||||
|
import android.os.Looper;
|
||||||
|
import android.preference.Preference;
|
||||||
|
import android.preference.PreferenceGroup;
|
||||||
|
import android.preference.PreferenceScreen;
|
||||||
|
import android.view.View;
|
||||||
|
import android.view.ViewGroup;
|
||||||
|
import android.view.ViewParent;
|
||||||
|
import android.view.animation.Animation;
|
||||||
|
import android.view.animation.AnimationUtils;
|
||||||
|
import android.widget.FrameLayout;
|
||||||
|
import android.widget.LinearLayout;
|
||||||
|
import android.widget.RelativeLayout;
|
||||||
|
import android.widget.Toast;
|
||||||
|
import android.widget.Toolbar;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import java.text.Bidi;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.SynchronousQueue;
|
||||||
|
import java.util.concurrent.ThreadPoolExecutor;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.settings.BooleanSetting;
|
||||||
|
import app.revanced.extension.shared.settings.preference.ReVancedAboutPreference;
|
||||||
|
|
||||||
|
public class Utils {
|
||||||
|
|
||||||
|
@SuppressLint("StaticFieldLeak")
|
||||||
|
private static Context context;
|
||||||
|
|
||||||
|
private static String versionName;
|
||||||
|
|
||||||
|
private Utils() {
|
||||||
|
} // utility class
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injection point.
|
||||||
|
*
|
||||||
|
* @return The manifest 'Version' entry of the patches.jar used during patching.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("SameReturnValue")
|
||||||
|
public static String getPatchesReleaseVersion() {
|
||||||
|
return ""; // Value is replaced during patching.
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return The version name of the app, such as 19.11.43
|
||||||
|
*/
|
||||||
|
public static String getAppVersionName() {
|
||||||
|
if (versionName == null) {
|
||||||
|
try {
|
||||||
|
final var packageName = Objects.requireNonNull(getContext()).getPackageName();
|
||||||
|
|
||||||
|
PackageManager packageManager = context.getPackageManager();
|
||||||
|
PackageInfo packageInfo;
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
packageInfo = packageManager.getPackageInfo(
|
||||||
|
packageName,
|
||||||
|
PackageManager.PackageInfoFlags.of(0)
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
packageInfo = packageManager.getPackageInfo(
|
||||||
|
packageName,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
versionName = packageInfo.versionName;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "Failed to get package info", ex);
|
||||||
|
versionName = "Unknown";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return versionName;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hide a view by setting its layout height and width to 1dp.
|
||||||
|
*
|
||||||
|
* @param condition The setting to check for hiding the view.
|
||||||
|
* @param view The view to hide.
|
||||||
|
*/
|
||||||
|
public static void hideViewBy0dpUnderCondition(BooleanSetting condition, View view) {
|
||||||
|
if (hideViewBy0dpUnderCondition(condition.get(), view)) {
|
||||||
|
Logger.printDebug(() -> "View hidden by setting: " + condition);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hide a view by setting its layout height and width to 0dp.
|
||||||
|
*
|
||||||
|
* @param condition The setting to check for hiding the view.
|
||||||
|
* @param view The view to hide.
|
||||||
|
*/
|
||||||
|
public static boolean hideViewBy0dpUnderCondition(boolean condition, View view) {
|
||||||
|
if (condition) {
|
||||||
|
hideViewByLayoutParams(view);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hide a view by setting its visibility to GONE.
|
||||||
|
*
|
||||||
|
* @param condition The setting to check for hiding the view.
|
||||||
|
* @param view The view to hide.
|
||||||
|
*/
|
||||||
|
public static void hideViewUnderCondition(BooleanSetting condition, View view) {
|
||||||
|
if (hideViewUnderCondition(condition.get(), view)) {
|
||||||
|
Logger.printDebug(() -> "View hidden by setting: " + condition);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hide a view by setting its visibility to GONE.
|
||||||
|
*
|
||||||
|
* @param condition The setting to check for hiding the view.
|
||||||
|
* @param view The view to hide.
|
||||||
|
*/
|
||||||
|
public static boolean hideViewUnderCondition(boolean condition, View view) {
|
||||||
|
if (condition) {
|
||||||
|
view.setVisibility(View.GONE);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void hideViewByRemovingFromParentUnderCondition(BooleanSetting condition, View view) {
|
||||||
|
if (hideViewByRemovingFromParentUnderCondition(condition.get(), view)) {
|
||||||
|
Logger.printDebug(() -> "View hidden by setting: " + condition);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean hideViewByRemovingFromParentUnderCondition(boolean setting, View view) {
|
||||||
|
if (setting) {
|
||||||
|
ViewParent parent = view.getParent();
|
||||||
|
if (parent instanceof ViewGroup) {
|
||||||
|
((ViewGroup) parent).removeView(view);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* General purpose pool for network calls and other background tasks.
|
||||||
|
* All tasks run at max thread priority.
|
||||||
|
*/
|
||||||
|
private static final ThreadPoolExecutor backgroundThreadPool = new ThreadPoolExecutor(
|
||||||
|
3, // 3 threads always ready to go
|
||||||
|
Integer.MAX_VALUE,
|
||||||
|
10, // For any threads over the minimum, keep them alive 10 seconds after they go idle
|
||||||
|
TimeUnit.SECONDS,
|
||||||
|
new SynchronousQueue<>(),
|
||||||
|
r -> { // ThreadFactory
|
||||||
|
Thread t = new Thread(r);
|
||||||
|
t.setPriority(Thread.MAX_PRIORITY); // run at max priority
|
||||||
|
return t;
|
||||||
|
});
|
||||||
|
|
||||||
|
public static void runOnBackgroundThread(@NonNull Runnable task) {
|
||||||
|
backgroundThreadPool.execute(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
public static <T> Future<T> submitOnBackgroundThread(@NonNull Callable<T> call) {
|
||||||
|
return backgroundThreadPool.submit(call);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simulates a delay by doing meaningless calculations.
|
||||||
|
* Used for debugging to verify UI timeout logic.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("UnusedReturnValue")
|
||||||
|
public static long doNothingForDuration(long amountOfTimeToWaste) {
|
||||||
|
final long timeCalculationStarted = System.currentTimeMillis();
|
||||||
|
Logger.printDebug(() -> "Artificially creating delay of: " + amountOfTimeToWaste + "ms");
|
||||||
|
|
||||||
|
long meaninglessValue = 0;
|
||||||
|
while (System.currentTimeMillis() - timeCalculationStarted < amountOfTimeToWaste) {
|
||||||
|
// could do a thread sleep, but that will trigger an exception if the thread is interrupted
|
||||||
|
meaninglessValue += Long.numberOfLeadingZeros((long) Math.exp(Math.random()));
|
||||||
|
}
|
||||||
|
// return the value, otherwise the compiler or VM might optimize and remove the meaningless time wasting work,
|
||||||
|
// leaving an empty loop that hammers on the System.currentTimeMillis native call
|
||||||
|
return meaninglessValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static boolean containsAny(@NonNull String value, @NonNull String... targets) {
|
||||||
|
return indexOfFirstFound(value, targets) >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int indexOfFirstFound(@NonNull String value, @NonNull String... targets) {
|
||||||
|
for (String string : targets) {
|
||||||
|
if (!string.isEmpty()) {
|
||||||
|
final int indexOf = value.indexOf(string);
|
||||||
|
if (indexOf >= 0) return indexOf;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return zero, if the resource is not found
|
||||||
|
*/
|
||||||
|
@SuppressLint("DiscouragedApi")
|
||||||
|
public static int getResourceIdentifier(@NonNull Context context, @NonNull String resourceIdentifierName, @NonNull String type) {
|
||||||
|
return context.getResources().getIdentifier(resourceIdentifierName, type, context.getPackageName());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return zero, if the resource is not found
|
||||||
|
*/
|
||||||
|
public static int getResourceIdentifier(@NonNull String resourceIdentifierName, @NonNull String type) {
|
||||||
|
return getResourceIdentifier(getContext(), resourceIdentifierName, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int getResourceInteger(@NonNull String resourceIdentifierName) throws Resources.NotFoundException {
|
||||||
|
return getContext().getResources().getInteger(getResourceIdentifier(resourceIdentifierName, "integer"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
public static Animation getResourceAnimation(@NonNull String resourceIdentifierName) throws Resources.NotFoundException {
|
||||||
|
return AnimationUtils.loadAnimation(getContext(), getResourceIdentifier(resourceIdentifierName, "anim"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int getResourceColor(@NonNull String resourceIdentifierName) throws Resources.NotFoundException {
|
||||||
|
//noinspection deprecation
|
||||||
|
return getContext().getResources().getColor(getResourceIdentifier(resourceIdentifierName, "color"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int getResourceDimensionPixelSize(@NonNull String resourceIdentifierName) throws Resources.NotFoundException {
|
||||||
|
return getContext().getResources().getDimensionPixelSize(getResourceIdentifier(resourceIdentifierName, "dimen"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static float getResourceDimension(@NonNull String resourceIdentifierName) throws Resources.NotFoundException {
|
||||||
|
return getContext().getResources().getDimension(getResourceIdentifier(resourceIdentifierName, "dimen"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public interface MatchFilter<T> {
|
||||||
|
boolean matches(T object);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Includes sub children.
|
||||||
|
*
|
||||||
|
* @noinspection unchecked
|
||||||
|
*/
|
||||||
|
public static <R extends View> R getChildViewByResourceName(@NonNull View view, @NonNull String str) {
|
||||||
|
var child = view.findViewById(Utils.getResourceIdentifier(str, "id"));
|
||||||
|
if (child != null) {
|
||||||
|
return (R) child;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new IllegalArgumentException("View with resource name '" + str + "' not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param searchRecursively If children ViewGroups should also be
|
||||||
|
* recursively searched using depth first search.
|
||||||
|
* @return The first child view that matches the filter.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
public static <T extends View> T getChildView(@NonNull ViewGroup viewGroup, boolean searchRecursively,
|
||||||
|
@NonNull MatchFilter<View> filter) {
|
||||||
|
for (int i = 0, childCount = viewGroup.getChildCount(); i < childCount; i++) {
|
||||||
|
View childAt = viewGroup.getChildAt(i);
|
||||||
|
|
||||||
|
if (filter.matches(childAt)) {
|
||||||
|
//noinspection unchecked
|
||||||
|
return (T) childAt;
|
||||||
|
}
|
||||||
|
// Must do recursive after filter check, in case the filter is looking for a ViewGroup.
|
||||||
|
if (searchRecursively && childAt instanceof ViewGroup) {
|
||||||
|
T match = getChildView((ViewGroup) childAt, true, filter);
|
||||||
|
if (match != null) return match;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
public static ViewParent getParentView(@NonNull View view, int nthParent) {
|
||||||
|
ViewParent parent = view.getParent();
|
||||||
|
|
||||||
|
int currentDepth = 0;
|
||||||
|
while (++currentDepth < nthParent && parent != null) {
|
||||||
|
parent = parent.getParent();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentDepth == nthParent) {
|
||||||
|
return parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
final int currentDepthLog = currentDepth;
|
||||||
|
Logger.printDebug(() -> "Could not find parent view of depth: " + nthParent
|
||||||
|
+ " and instead found at: " + currentDepthLog + " view: " + view);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void restartApp(@NonNull Context context) {
|
||||||
|
String packageName = context.getPackageName();
|
||||||
|
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
|
||||||
|
Intent mainIntent = Intent.makeRestartActivityTask(intent.getComponent());
|
||||||
|
// Required for API 34 and later
|
||||||
|
// Ref: https://developer.android.com/about/versions/14/behavior-changes-14#safer-intents
|
||||||
|
mainIntent.setPackage(packageName);
|
||||||
|
context.startActivity(mainIntent);
|
||||||
|
System.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Context getContext() {
|
||||||
|
if (context == null) {
|
||||||
|
Logger.initializationException(Utils.class, "Context is null, returning null!", null);
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void setContext(Context appContext) {
|
||||||
|
context = appContext;
|
||||||
|
// In some apps like TikTok, the Setting classes can load in weird orders due to cyclic class dependencies.
|
||||||
|
// Calling the regular printDebug method here can cause a Settings context null pointer exception,
|
||||||
|
// even though the context is already set before the call.
|
||||||
|
//
|
||||||
|
// The initialization logger methods do not directly or indirectly
|
||||||
|
// reference the Context or any Settings and are unaffected by this problem.
|
||||||
|
//
|
||||||
|
// Info level also helps debug if a patch hook is called before
|
||||||
|
// the context is set since debug logging is off by default.
|
||||||
|
Logger.initializationInfo(Utils.class, "Set context: " + appContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void setClipboard(@NonNull String text) {
|
||||||
|
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
|
||||||
|
android.content.ClipData clip = android.content.ClipData.newPlainText("ReVanced", text);
|
||||||
|
clipboard.setPrimaryClip(clip);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isTablet() {
|
||||||
|
return context.getResources().getConfiguration().smallestScreenWidthDp >= 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
private static Boolean isRightToLeftTextLayout;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the device language uses right to left text layout (hebrew, arabic, etc)
|
||||||
|
*/
|
||||||
|
public static boolean isRightToLeftTextLayout() {
|
||||||
|
if (isRightToLeftTextLayout == null) {
|
||||||
|
String displayLanguage = Locale.getDefault().getDisplayLanguage();
|
||||||
|
isRightToLeftTextLayout = new Bidi(displayLanguage, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT).isRightToLeft();
|
||||||
|
}
|
||||||
|
return isRightToLeftTextLayout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return if the text contains at least 1 number character,
|
||||||
|
* including any unicode numbers such as Arabic.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
|
||||||
|
public static boolean containsNumber(@NonNull CharSequence text) {
|
||||||
|
for (int index = 0, length = text.length(); index < length;) {
|
||||||
|
final int codePoint = Character.codePointAt(text, index);
|
||||||
|
if (Character.isDigit(codePoint)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
index += Character.charCount(codePoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ignore this class. It must be public to satisfy Android requirements.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public static final class DialogFragmentWrapper extends DialogFragment {
|
||||||
|
|
||||||
|
private Dialog dialog;
|
||||||
|
@Nullable
|
||||||
|
private DialogFragmentOnStartAction onStartAction;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onSaveInstanceState(Bundle outState) {
|
||||||
|
// Do not call super method to prevent state saving.
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
public Dialog onCreateDialog(Bundle savedInstanceState) {
|
||||||
|
return dialog;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onStart() {
|
||||||
|
try {
|
||||||
|
super.onStart();
|
||||||
|
|
||||||
|
if (onStartAction != null) {
|
||||||
|
onStartAction.onStart((AlertDialog) getDialog());
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "onStart failure: " + dialog.getClass().getSimpleName(), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface for {@link #showDialog(Activity, AlertDialog, boolean, DialogFragmentOnStartAction)}.
|
||||||
|
*/
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface DialogFragmentOnStartAction {
|
||||||
|
void onStart(AlertDialog dialog);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void showDialog(Activity activity, AlertDialog dialog) {
|
||||||
|
showDialog(activity, dialog, true, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utility method to allow showing an AlertDialog on top of other alert dialogs.
|
||||||
|
* Calling this will always display the dialog on top of all other dialogs
|
||||||
|
* previously called using this method.
|
||||||
|
* <br>
|
||||||
|
* Be aware the on start action can be called multiple times for some situations,
|
||||||
|
* such as the user switching apps without dismissing the dialog then switching back to this app.
|
||||||
|
*<br>
|
||||||
|
* This method is only useful during app startup and multiple patches may show their own dialog,
|
||||||
|
* and the most important dialog can be called last (using a delay) so it's always on top.
|
||||||
|
*<br>
|
||||||
|
* For all other situations it's better to not use this method and
|
||||||
|
* call {@link AlertDialog#show()} on the dialog.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public static void showDialog(Activity activity,
|
||||||
|
AlertDialog dialog,
|
||||||
|
boolean isCancelable,
|
||||||
|
@Nullable DialogFragmentOnStartAction onStartAction) {
|
||||||
|
verifyOnMainThread();
|
||||||
|
|
||||||
|
DialogFragmentWrapper fragment = new DialogFragmentWrapper();
|
||||||
|
fragment.dialog = dialog;
|
||||||
|
fragment.onStartAction = onStartAction;
|
||||||
|
fragment.setCancelable(isCancelable);
|
||||||
|
|
||||||
|
fragment.show(activity.getFragmentManager(), null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Safe to call from any thread
|
||||||
|
*/
|
||||||
|
public static void showToastShort(@NonNull String messageToToast) {
|
||||||
|
showToast(messageToToast, Toast.LENGTH_SHORT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Safe to call from any thread
|
||||||
|
*/
|
||||||
|
public static void showToastLong(@NonNull String messageToToast) {
|
||||||
|
showToast(messageToToast, Toast.LENGTH_LONG);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void showToast(@NonNull String messageToToast, int toastDuration) {
|
||||||
|
Objects.requireNonNull(messageToToast);
|
||||||
|
runOnMainThreadNowOrLater(() -> {
|
||||||
|
if (context == null) {
|
||||||
|
Logger.initializationException(Utils.class, "Cannot show toast (context is null): " + messageToToast, null);
|
||||||
|
} else {
|
||||||
|
Logger.printDebug(() -> "Showing toast: " + messageToToast);
|
||||||
|
Toast.makeText(context, messageToToast, toastDuration).show();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Automatically logs any exceptions the runnable throws.
|
||||||
|
*
|
||||||
|
* @see #runOnMainThreadNowOrLater(Runnable)
|
||||||
|
*/
|
||||||
|
public static void runOnMainThread(@NonNull Runnable runnable) {
|
||||||
|
runOnMainThreadDelayed(runnable, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Automatically logs any exceptions the runnable throws
|
||||||
|
*/
|
||||||
|
public static void runOnMainThreadDelayed(@NonNull Runnable runnable, long delayMillis) {
|
||||||
|
Runnable loggingRunnable = () -> {
|
||||||
|
try {
|
||||||
|
runnable.run();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> runnable.getClass().getSimpleName() + ": " + ex.getMessage(), ex);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
new Handler(Looper.getMainLooper()).postDelayed(loggingRunnable, delayMillis);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If called from the main thread, the code is run immediately.<p>
|
||||||
|
* If called off the main thread, this is the same as {@link #runOnMainThread(Runnable)}.
|
||||||
|
*/
|
||||||
|
public static void runOnMainThreadNowOrLater(@NonNull Runnable runnable) {
|
||||||
|
if (isCurrentlyOnMainThread()) {
|
||||||
|
runnable.run();
|
||||||
|
} else {
|
||||||
|
runOnMainThread(runnable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return if the calling thread is on the main thread
|
||||||
|
*/
|
||||||
|
public static boolean isCurrentlyOnMainThread() {
|
||||||
|
return Looper.getMainLooper().isCurrentThread();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws IllegalStateException if the calling thread is _off_ the main thread
|
||||||
|
*/
|
||||||
|
public static void verifyOnMainThread() throws IllegalStateException {
|
||||||
|
if (!isCurrentlyOnMainThread()) {
|
||||||
|
throw new IllegalStateException("Must call _on_ the main thread");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws IllegalStateException if the calling thread is _on_ the main thread
|
||||||
|
*/
|
||||||
|
public static void verifyOffMainThread() throws IllegalStateException {
|
||||||
|
if (isCurrentlyOnMainThread()) {
|
||||||
|
throw new IllegalStateException("Must call _off_ the main thread");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum NetworkType {
|
||||||
|
NONE,
|
||||||
|
MOBILE,
|
||||||
|
OTHER,
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isNetworkConnected() {
|
||||||
|
NetworkType networkType = getNetworkType();
|
||||||
|
return networkType == NetworkType.MOBILE
|
||||||
|
|| networkType == NetworkType.OTHER;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("MissingPermission") // permission already included in YouTube
|
||||||
|
public static NetworkType getNetworkType() {
|
||||||
|
Context networkContext = getContext();
|
||||||
|
if (networkContext == null) {
|
||||||
|
return NetworkType.NONE;
|
||||||
|
}
|
||||||
|
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||||
|
var networkInfo = cm.getActiveNetworkInfo();
|
||||||
|
|
||||||
|
if (networkInfo == null || !networkInfo.isConnected()) {
|
||||||
|
return NetworkType.NONE;
|
||||||
|
}
|
||||||
|
var type = networkInfo.getType();
|
||||||
|
return (type == ConnectivityManager.TYPE_MOBILE)
|
||||||
|
|| (type == ConnectivityManager.TYPE_BLUETOOTH) ? NetworkType.MOBILE : NetworkType.OTHER;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hide a view by setting its layout params to 0x0
|
||||||
|
* @param view The view to hide.
|
||||||
|
*/
|
||||||
|
public static void hideViewByLayoutParams(View view) {
|
||||||
|
if (view instanceof LinearLayout) {
|
||||||
|
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, 0);
|
||||||
|
view.setLayoutParams(layoutParams);
|
||||||
|
} else if (view instanceof FrameLayout) {
|
||||||
|
FrameLayout.LayoutParams layoutParams2 = new FrameLayout.LayoutParams(0, 0);
|
||||||
|
view.setLayoutParams(layoutParams2);
|
||||||
|
} else if (view instanceof RelativeLayout) {
|
||||||
|
RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(0, 0);
|
||||||
|
view.setLayoutParams(layoutParams3);
|
||||||
|
} else if (view instanceof Toolbar) {
|
||||||
|
Toolbar.LayoutParams layoutParams4 = new Toolbar.LayoutParams(0, 0);
|
||||||
|
view.setLayoutParams(layoutParams4);
|
||||||
|
} else if (view instanceof ViewGroup) {
|
||||||
|
ViewGroup.LayoutParams layoutParams5 = new ViewGroup.LayoutParams(0, 0);
|
||||||
|
view.setLayoutParams(layoutParams5);
|
||||||
|
} else {
|
||||||
|
ViewGroup.LayoutParams params = view.getLayoutParams();
|
||||||
|
params.width = 0;
|
||||||
|
params.height = 0;
|
||||||
|
view.setLayoutParams(params);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link PreferenceScreen} and {@link PreferenceGroup} sorting styles.
|
||||||
|
*/
|
||||||
|
private enum Sort {
|
||||||
|
/**
|
||||||
|
* Sort by the localized preference title.
|
||||||
|
*/
|
||||||
|
BY_TITLE("_sort_by_title"),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sort by the preference keys.
|
||||||
|
*/
|
||||||
|
BY_KEY("_sort_by_key"),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unspecified sorting.
|
||||||
|
*/
|
||||||
|
UNSORTED("_sort_by_unsorted");
|
||||||
|
|
||||||
|
final String keySuffix;
|
||||||
|
|
||||||
|
Sort(String keySuffix) {
|
||||||
|
this.keySuffix = keySuffix;
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
static Sort fromKey(@Nullable String key, @NonNull Sort defaultSort) {
|
||||||
|
if (key != null) {
|
||||||
|
for (Sort sort : values()) {
|
||||||
|
if (key.endsWith(sort.keySuffix)) {
|
||||||
|
return sort;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return defaultSort;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final Pattern punctuationPattern = Pattern.compile("\\p{P}+");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strips all punctuation and converts to lower case. A null parameter returns an empty string.
|
||||||
|
*/
|
||||||
|
public static String removePunctuationConvertToLowercase(@Nullable CharSequence original) {
|
||||||
|
if (original == null) return "";
|
||||||
|
return punctuationPattern.matcher(original).replaceAll("").toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sort a PreferenceGroup and all it's sub groups by title or key.
|
||||||
|
*
|
||||||
|
* Sort order is determined by the preferences key {@link Sort} suffix.
|
||||||
|
*
|
||||||
|
* If a preference has no key or no {@link Sort} suffix,
|
||||||
|
* then the preferences are left unsorted.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public static void sortPreferenceGroups(@NonNull PreferenceGroup group) {
|
||||||
|
Sort groupSort = Sort.fromKey(group.getKey(), Sort.UNSORTED);
|
||||||
|
SortedMap<String, Preference> preferences = new TreeMap<>();
|
||||||
|
|
||||||
|
for (int i = 0, prefCount = group.getPreferenceCount(); i < prefCount; i++) {
|
||||||
|
Preference preference = group.getPreference(i);
|
||||||
|
|
||||||
|
final Sort preferenceSort;
|
||||||
|
if (preference instanceof PreferenceGroup) {
|
||||||
|
sortPreferenceGroups((PreferenceGroup) preference);
|
||||||
|
preferenceSort = groupSort; // Sort value for groups is for it's content, not itself.
|
||||||
|
} else {
|
||||||
|
// Allow individual preferences to set a key sorting.
|
||||||
|
// Used to force a preference to the top or bottom of a group.
|
||||||
|
preferenceSort = Sort.fromKey(preference.getKey(), groupSort);
|
||||||
|
}
|
||||||
|
|
||||||
|
final String sortValue;
|
||||||
|
switch (preferenceSort) {
|
||||||
|
case BY_TITLE:
|
||||||
|
sortValue = removePunctuationConvertToLowercase(preference.getTitle());
|
||||||
|
break;
|
||||||
|
case BY_KEY:
|
||||||
|
sortValue = preference.getKey();
|
||||||
|
break;
|
||||||
|
case UNSORTED:
|
||||||
|
continue; // Keep original sorting.
|
||||||
|
default:
|
||||||
|
throw new IllegalStateException();
|
||||||
|
}
|
||||||
|
|
||||||
|
preferences.put(sortValue, preference);
|
||||||
|
}
|
||||||
|
|
||||||
|
int index = 0;
|
||||||
|
for (Preference pref : preferences.values()) {
|
||||||
|
int order = index++;
|
||||||
|
|
||||||
|
// Move any screens, intents, and the one off About preference to the top.
|
||||||
|
if (pref instanceof PreferenceScreen || pref instanceof ReVancedAboutPreference
|
||||||
|
|| pref.getIntent() != null) {
|
||||||
|
// Arbitrary high number.
|
||||||
|
order -= 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
pref.setOrder(order);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If {@link Fragment} uses [Android library] rather than [AndroidX library],
|
||||||
|
* the Dialog theme corresponding to [Android library] should be used.
|
||||||
|
* <p>
|
||||||
|
* If not, the following issues will occur:
|
||||||
|
* <a href="https://github.com/ReVanced/revanced-patches/issues/3061">ReVanced/revanced-patches#3061</a>
|
||||||
|
* <p>
|
||||||
|
* To prevent these issues, apply the Dialog theme corresponding to [Android library].
|
||||||
|
*/
|
||||||
|
public static void setEditTextDialogTheme(AlertDialog.Builder builder) {
|
||||||
|
final int editTextDialogStyle = getResourceIdentifier(
|
||||||
|
"revanced_edit_text_dialog_style", "style");
|
||||||
|
if (editTextDialogStyle != 0) {
|
||||||
|
builder.getContext().setTheme(editTextDialogStyle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,164 @@
|
|||||||
|
package app.revanced.extension.shared.checks;
|
||||||
|
|
||||||
|
import static android.text.Html.FROM_HTML_MODE_COMPACT;
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
import static app.revanced.extension.shared.Utils.DialogFragmentOnStartAction;
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint;
|
||||||
|
import android.app.Activity;
|
||||||
|
import android.app.AlertDialog;
|
||||||
|
import android.content.DialogInterface;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.net.Uri;
|
||||||
|
import android.text.Html;
|
||||||
|
import android.widget.Button;
|
||||||
|
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
import app.revanced.extension.youtube.settings.Settings;
|
||||||
|
|
||||||
|
abstract class Check {
|
||||||
|
private static final int NUMBER_OF_TIMES_TO_IGNORE_WARNING_BEFORE_DISABLING = 2;
|
||||||
|
|
||||||
|
private static final int SECONDS_BEFORE_SHOWING_IGNORE_BUTTON = 15;
|
||||||
|
private static final int SECONDS_BEFORE_SHOWING_WEBSITE_BUTTON = 10;
|
||||||
|
|
||||||
|
private static final Uri GOOD_SOURCE = Uri.parse("https://revanced.app");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return If the check conclusively passed or failed. A null value indicates it neither passed nor failed.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
protected abstract Boolean check();
|
||||||
|
|
||||||
|
protected abstract String failureReason();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Specifies a sorting order for displaying the checks that failed.
|
||||||
|
* A lower value indicates to show first before other checks.
|
||||||
|
*/
|
||||||
|
public abstract int uiSortingValue();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* For debugging and development only.
|
||||||
|
* Forces all checks to be performed and the check failed dialog to be shown.
|
||||||
|
* Can be enabled by importing settings text with {@link Settings#CHECK_ENVIRONMENT_WARNINGS_ISSUED}
|
||||||
|
* set to -1.
|
||||||
|
*/
|
||||||
|
static boolean debugAlwaysShowWarning() {
|
||||||
|
final boolean alwaysShowWarning = Settings.CHECK_ENVIRONMENT_WARNINGS_ISSUED.get() < 0;
|
||||||
|
if (alwaysShowWarning) {
|
||||||
|
Logger.printInfo(() -> "Debug forcing environment check warning to show");
|
||||||
|
}
|
||||||
|
|
||||||
|
return alwaysShowWarning;
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean shouldRun() {
|
||||||
|
return Settings.CHECK_ENVIRONMENT_WARNINGS_ISSUED.get()
|
||||||
|
< NUMBER_OF_TIMES_TO_IGNORE_WARNING_BEFORE_DISABLING;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void disableForever() {
|
||||||
|
Logger.printInfo(() -> "Environment checks disabled forever");
|
||||||
|
|
||||||
|
Settings.CHECK_ENVIRONMENT_WARNINGS_ISSUED.save(Integer.MAX_VALUE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NewApi")
|
||||||
|
static void issueWarning(Activity activity, Collection<Check> failedChecks) {
|
||||||
|
final var reasons = new StringBuilder();
|
||||||
|
|
||||||
|
reasons.append("<ul>");
|
||||||
|
for (var check : failedChecks) {
|
||||||
|
// Add a non breaking space to fix bullet points spacing issue.
|
||||||
|
reasons.append("<li> ").append(check.failureReason());
|
||||||
|
}
|
||||||
|
reasons.append("</ul>");
|
||||||
|
|
||||||
|
var message = Html.fromHtml(
|
||||||
|
str("revanced_check_environment_failed_message", reasons.toString()),
|
||||||
|
FROM_HTML_MODE_COMPACT
|
||||||
|
);
|
||||||
|
|
||||||
|
Utils.runOnMainThreadDelayed(() -> {
|
||||||
|
AlertDialog alert = new AlertDialog.Builder(activity)
|
||||||
|
.setCancelable(false)
|
||||||
|
.setIconAttribute(android.R.attr.alertDialogIcon)
|
||||||
|
.setTitle(str("revanced_check_environment_failed_title"))
|
||||||
|
.setMessage(message)
|
||||||
|
.setPositiveButton(
|
||||||
|
" ",
|
||||||
|
(dialog, which) -> {
|
||||||
|
final var intent = new Intent(Intent.ACTION_VIEW, GOOD_SOURCE);
|
||||||
|
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||||
|
activity.startActivity(intent);
|
||||||
|
|
||||||
|
// Shutdown to prevent the user from navigating back to this app,
|
||||||
|
// which is no longer showing a warning dialog.
|
||||||
|
activity.finishAffinity();
|
||||||
|
System.exit(0);
|
||||||
|
}
|
||||||
|
).setNegativeButton(
|
||||||
|
" ",
|
||||||
|
(dialog, which) -> {
|
||||||
|
// Cleanup data if the user incorrectly imported a huge negative number.
|
||||||
|
final int current = Math.max(0, Settings.CHECK_ENVIRONMENT_WARNINGS_ISSUED.get());
|
||||||
|
Settings.CHECK_ENVIRONMENT_WARNINGS_ISSUED.save(current + 1);
|
||||||
|
|
||||||
|
dialog.dismiss();
|
||||||
|
}
|
||||||
|
).create();
|
||||||
|
|
||||||
|
Utils.showDialog(activity, alert, false, new DialogFragmentOnStartAction() {
|
||||||
|
boolean hasRun;
|
||||||
|
@Override
|
||||||
|
public void onStart(AlertDialog dialog) {
|
||||||
|
// Only run this once, otherwise if the user changes to a different app
|
||||||
|
// then changes back, this handler will run again and disable the buttons.
|
||||||
|
if (hasRun) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hasRun = true;
|
||||||
|
|
||||||
|
var openWebsiteButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
|
||||||
|
openWebsiteButton.setEnabled(false);
|
||||||
|
|
||||||
|
var dismissButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
|
||||||
|
dismissButton.setEnabled(false);
|
||||||
|
|
||||||
|
getCountdownRunnable(dismissButton, openWebsiteButton).run();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, 1000); // Use a delay, so this dialog is shown on top of any other startup dialogs.
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Runnable getCountdownRunnable(Button dismissButton, Button openWebsiteButton) {
|
||||||
|
return new Runnable() {
|
||||||
|
private int secondsRemaining = SECONDS_BEFORE_SHOWING_IGNORE_BUTTON;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
Utils.verifyOnMainThread();
|
||||||
|
|
||||||
|
if (secondsRemaining > 0) {
|
||||||
|
if (secondsRemaining - SECONDS_BEFORE_SHOWING_WEBSITE_BUTTON == 0) {
|
||||||
|
openWebsiteButton.setText(str("revanced_check_environment_dialog_open_official_source_button"));
|
||||||
|
openWebsiteButton.setEnabled(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
secondsRemaining--;
|
||||||
|
|
||||||
|
Utils.runOnMainThreadDelayed(this, 1000);
|
||||||
|
} else {
|
||||||
|
dismissButton.setText(str("revanced_check_environment_dialog_ignore_button"));
|
||||||
|
dismissButton.setEnabled(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,341 @@
|
|||||||
|
package app.revanced.extension.shared.checks;
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint;
|
||||||
|
import android.app.Activity;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.pm.PackageInfo;
|
||||||
|
import android.content.pm.PackageManager;
|
||||||
|
import android.os.Build;
|
||||||
|
import android.util.Base64;
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
import static app.revanced.extension.shared.checks.Check.debugAlwaysShowWarning;
|
||||||
|
import static app.revanced.extension.shared.checks.PatchInfo.Build.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This class is used to check if the app was patched by the user
|
||||||
|
* and not downloaded pre-patched, because pre-patched apps are difficult to trust.
|
||||||
|
* <br>
|
||||||
|
* Various indicators help to detect if the app was patched by the user.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public final class CheckEnvironmentPatch {
|
||||||
|
private static final boolean DEBUG_ALWAYS_SHOW_CHECK_FAILED_DIALOG = debugAlwaysShowWarning();
|
||||||
|
|
||||||
|
private enum InstallationType {
|
||||||
|
/**
|
||||||
|
* CLI patching, manual installation of a previously patched using adb,
|
||||||
|
* or root installation if stock app is first installed using adb.
|
||||||
|
*/
|
||||||
|
ADB((String) null),
|
||||||
|
ROOT_MOUNT_ON_APP_STORE("com.android.vending"),
|
||||||
|
MANAGER("app.revanced.manager.flutter",
|
||||||
|
"app.revanced.manager",
|
||||||
|
"app.revanced.manager.debug");
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
static InstallationType installTypeFromPackageName(@Nullable String packageName) {
|
||||||
|
for (InstallationType type : values()) {
|
||||||
|
for (String installPackageName : type.packageNames) {
|
||||||
|
if (Objects.equals(installPackageName, packageName)) {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Array elements can be null.
|
||||||
|
*/
|
||||||
|
final String[] packageNames;
|
||||||
|
|
||||||
|
InstallationType(String... packageNames) {
|
||||||
|
this.packageNames = packageNames;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the app is installed by the manager, the app store, or through adb/CLI.
|
||||||
|
* <br>
|
||||||
|
* Does not conclusively
|
||||||
|
* If the app is installed by the manager or the app store, it is likely, the app was patched using the manager,
|
||||||
|
* or installed manually via ADB (in the case of ReVanced CLI for example).
|
||||||
|
* <br>
|
||||||
|
* If the app is not installed by the manager or the app store, then the app was likely downloaded pre-patched
|
||||||
|
* and installed by the browser or another unknown app.
|
||||||
|
*/
|
||||||
|
private static class CheckExpectedInstaller extends Check {
|
||||||
|
@Nullable
|
||||||
|
InstallationType installerFound;
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
protected Boolean check() {
|
||||||
|
final var context = Utils.getContext();
|
||||||
|
|
||||||
|
final var installerPackageName =
|
||||||
|
context.getPackageManager().getInstallerPackageName(context.getPackageName());
|
||||||
|
|
||||||
|
Logger.printInfo(() -> "Installed by: " + installerPackageName);
|
||||||
|
|
||||||
|
installerFound = InstallationType.installTypeFromPackageName(installerPackageName);
|
||||||
|
final boolean passed = (installerFound != null);
|
||||||
|
|
||||||
|
Logger.printInfo(() -> passed
|
||||||
|
? "Apk was not installed from an unknown source"
|
||||||
|
: "Apk was installed from an unknown source");
|
||||||
|
|
||||||
|
return passed;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String failureReason() {
|
||||||
|
return str("revanced_check_environment_manager_not_expected_installer");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int uiSortingValue() {
|
||||||
|
return -100; // Show first.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the build properties are the same as during the patch.
|
||||||
|
* <br>
|
||||||
|
* If the build properties are the same as during the patch, it is likely, the app was patched on the same device.
|
||||||
|
* <br>
|
||||||
|
* If the build properties are different, the app was likely downloaded pre-patched or patched on another device.
|
||||||
|
*/
|
||||||
|
private static class CheckWasPatchedOnSameDevice extends Check {
|
||||||
|
@SuppressLint({"NewApi", "HardwareIds"})
|
||||||
|
@Override
|
||||||
|
protected Boolean check() {
|
||||||
|
if (PATCH_BOARD.isEmpty()) {
|
||||||
|
// Did not patch with Manager, and cannot conclusively say where this was from.
|
||||||
|
Logger.printInfo(() -> "APK does not contain a hardware signature and cannot compare to current device");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
//noinspection deprecation
|
||||||
|
final var passed = buildFieldEqualsHash("BOARD", Build.BOARD, PATCH_BOARD) &
|
||||||
|
buildFieldEqualsHash("BOOTLOADER", Build.BOOTLOADER, PATCH_BOOTLOADER) &
|
||||||
|
buildFieldEqualsHash("BRAND", Build.BRAND, PATCH_BRAND) &
|
||||||
|
buildFieldEqualsHash("CPU_ABI", Build.CPU_ABI, PATCH_CPU_ABI) &
|
||||||
|
buildFieldEqualsHash("CPU_ABI2", Build.CPU_ABI2, PATCH_CPU_ABI2) &
|
||||||
|
buildFieldEqualsHash("DEVICE", Build.DEVICE, PATCH_DEVICE) &
|
||||||
|
buildFieldEqualsHash("DISPLAY", Build.DISPLAY, PATCH_DISPLAY) &
|
||||||
|
buildFieldEqualsHash("FINGERPRINT", Build.FINGERPRINT, PATCH_FINGERPRINT) &
|
||||||
|
buildFieldEqualsHash("HARDWARE", Build.HARDWARE, PATCH_HARDWARE) &
|
||||||
|
buildFieldEqualsHash("HOST", Build.HOST, PATCH_HOST) &
|
||||||
|
buildFieldEqualsHash("ID", Build.ID, PATCH_ID) &
|
||||||
|
buildFieldEqualsHash("MANUFACTURER", Build.MANUFACTURER, PATCH_MANUFACTURER) &
|
||||||
|
buildFieldEqualsHash("MODEL", Build.MODEL, PATCH_MODEL) &
|
||||||
|
buildFieldEqualsHash("PRODUCT", Build.PRODUCT, PATCH_PRODUCT) &
|
||||||
|
buildFieldEqualsHash("RADIO", Build.RADIO, PATCH_RADIO) &
|
||||||
|
buildFieldEqualsHash("TAGS", Build.TAGS, PATCH_TAGS) &
|
||||||
|
buildFieldEqualsHash("TYPE", Build.TYPE, PATCH_TYPE) &
|
||||||
|
buildFieldEqualsHash("USER", Build.USER, PATCH_USER);
|
||||||
|
|
||||||
|
Logger.printInfo(() -> passed
|
||||||
|
? "Device hardware signature matches current device"
|
||||||
|
: "Device hardware signature does not match current device");
|
||||||
|
|
||||||
|
return passed;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String failureReason() {
|
||||||
|
return str("revanced_check_environment_not_same_patching_device");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int uiSortingValue() {
|
||||||
|
return 0; // Show in the middle.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the app was installed within the last 30 minutes after being patched.
|
||||||
|
* <br>
|
||||||
|
* If the app was installed within the last 30 minutes, it is likely, the app was patched by the user.
|
||||||
|
* <br>
|
||||||
|
* If the app was installed much later than the patch time, it is likely the app was
|
||||||
|
* downloaded pre-patched or the user waited too long to install the app.
|
||||||
|
*/
|
||||||
|
private static class CheckIsNearPatchTime extends Check {
|
||||||
|
/**
|
||||||
|
* How soon after patching the app must be installed to pass.
|
||||||
|
*/
|
||||||
|
static final int INSTALL_AFTER_PATCHING_DURATION_THRESHOLD = 30 * 60 * 1000; // 30 minutes.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Milliseconds between the time the app was patched, and when it was installed/updated.
|
||||||
|
*/
|
||||||
|
long durationBetweenPatchingAndInstallation;
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
protected Boolean check() {
|
||||||
|
try {
|
||||||
|
Context context = Utils.getContext();
|
||||||
|
PackageManager packageManager = context.getPackageManager();
|
||||||
|
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
|
||||||
|
|
||||||
|
// Duration since initial install or last update, which ever is sooner.
|
||||||
|
durationBetweenPatchingAndInstallation = packageInfo.lastUpdateTime - PatchInfo.PATCH_TIME;
|
||||||
|
Logger.printInfo(() -> "App was installed/updated: "
|
||||||
|
+ (durationBetweenPatchingAndInstallation / (60 * 1000) + " minutes after patching"));
|
||||||
|
|
||||||
|
if (durationBetweenPatchingAndInstallation < 0) {
|
||||||
|
// Patch time is in the future and clearly wrong.
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (durationBetweenPatchingAndInstallation < INSTALL_AFTER_PATCHING_DURATION_THRESHOLD) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch (PackageManager.NameNotFoundException ex) {
|
||||||
|
Logger.printException(() -> "Package name not found exception", ex); // Will never happen.
|
||||||
|
}
|
||||||
|
|
||||||
|
// User installed more than 30 minutes after patching.
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String failureReason() {
|
||||||
|
if (durationBetweenPatchingAndInstallation < 0) {
|
||||||
|
// Could happen if the user has their device clock incorrectly set in the past,
|
||||||
|
// but assume that isn't the case and the apk was patched on a device with the wrong system time.
|
||||||
|
return str("revanced_check_environment_not_near_patch_time_invalid");
|
||||||
|
}
|
||||||
|
|
||||||
|
// If patched over 1 day ago, show how old this pre-patched apk is.
|
||||||
|
// Showing the age can help convey it's better to patch yourself and know it's the latest.
|
||||||
|
final long oneDay = 24 * 60 * 60 * 1000;
|
||||||
|
final long daysSincePatching = durationBetweenPatchingAndInstallation / oneDay;
|
||||||
|
if (daysSincePatching > 1) { // Use over 1 day to avoid singular vs plural strings.
|
||||||
|
return str("revanced_check_environment_not_near_patch_time_days", daysSincePatching);
|
||||||
|
}
|
||||||
|
|
||||||
|
return str("revanced_check_environment_not_near_patch_time");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int uiSortingValue() {
|
||||||
|
return 100; // Show last.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injection point.
|
||||||
|
*/
|
||||||
|
public static void check(Activity context) {
|
||||||
|
// If the warning was already issued twice, or if the check was successful in the past,
|
||||||
|
// do not run the checks again.
|
||||||
|
if (!Check.shouldRun() && !DEBUG_ALWAYS_SHOW_CHECK_FAILED_DIALOG) {
|
||||||
|
Logger.printDebug(() -> "Environment checks are disabled");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Utils.runOnBackgroundThread(() -> {
|
||||||
|
try {
|
||||||
|
Logger.printInfo(() -> "Running environment checks");
|
||||||
|
List<Check> failedChecks = new ArrayList<>();
|
||||||
|
|
||||||
|
CheckWasPatchedOnSameDevice sameHardware = new CheckWasPatchedOnSameDevice();
|
||||||
|
Boolean hardwareCheckPassed = sameHardware.check();
|
||||||
|
if (hardwareCheckPassed != null) {
|
||||||
|
if (hardwareCheckPassed && !DEBUG_ALWAYS_SHOW_CHECK_FAILED_DIALOG) {
|
||||||
|
// Patched on the same device using Manager,
|
||||||
|
// and no further checks are needed.
|
||||||
|
Check.disableForever();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
failedChecks.add(sameHardware);
|
||||||
|
}
|
||||||
|
|
||||||
|
CheckExpectedInstaller installerCheck = new CheckExpectedInstaller();
|
||||||
|
if (installerCheck.check() && !DEBUG_ALWAYS_SHOW_CHECK_FAILED_DIALOG) {
|
||||||
|
// If the installer package is Manager but this code is reached,
|
||||||
|
// that means it must not be the right Manager otherwise the hardware hash
|
||||||
|
// signatures would be present and this check would not have run.
|
||||||
|
if (installerCheck.installerFound == InstallationType.MANAGER) {
|
||||||
|
failedChecks.add(installerCheck);
|
||||||
|
// Also could not have been patched on this device.
|
||||||
|
failedChecks.add(sameHardware);
|
||||||
|
} else if (failedChecks.isEmpty()) {
|
||||||
|
// ADB install of CLI build. Allow even if patched a long time ago.
|
||||||
|
Check.disableForever();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
failedChecks.add(installerCheck);
|
||||||
|
}
|
||||||
|
|
||||||
|
CheckIsNearPatchTime nearPatchTime = new CheckIsNearPatchTime();
|
||||||
|
Boolean timeCheckPassed = nearPatchTime.check();
|
||||||
|
if (timeCheckPassed && !DEBUG_ALWAYS_SHOW_CHECK_FAILED_DIALOG) {
|
||||||
|
// Allow installing recently patched apks,
|
||||||
|
// even if the install source is not Manager or ADB.
|
||||||
|
Check.disableForever();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
failedChecks.add(nearPatchTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (DEBUG_ALWAYS_SHOW_CHECK_FAILED_DIALOG) {
|
||||||
|
// Show all failures for debugging layout.
|
||||||
|
failedChecks = Arrays.asList(
|
||||||
|
sameHardware,
|
||||||
|
nearPatchTime,
|
||||||
|
installerCheck
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
//noinspection ComparatorCombinators
|
||||||
|
Collections.sort(failedChecks, (o1, o2) -> o1.uiSortingValue() - o2.uiSortingValue());
|
||||||
|
|
||||||
|
Check.issueWarning(
|
||||||
|
context,
|
||||||
|
failedChecks
|
||||||
|
);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "check failure", ex);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean buildFieldEqualsHash(String buildFieldName, String buildFieldValue, @Nullable String hash) {
|
||||||
|
try {
|
||||||
|
final var sha1 = MessageDigest.getInstance("SHA-1")
|
||||||
|
.digest(buildFieldValue.getBytes(StandardCharsets.UTF_8));
|
||||||
|
|
||||||
|
// Must be careful to use same base64 encoding Kotlin uses.
|
||||||
|
String runtimeHash = new String(Base64.encode(sha1, Base64.NO_WRAP), StandardCharsets.ISO_8859_1);
|
||||||
|
final boolean equals = runtimeHash.equals(hash);
|
||||||
|
if (!equals) {
|
||||||
|
Logger.printInfo(() -> "Hashes do not match. " + buildFieldName + ": '" + buildFieldValue
|
||||||
|
+ "' runtimeHash: '" + runtimeHash + "' patchTimeHash: '" + hash + "'");
|
||||||
|
}
|
||||||
|
|
||||||
|
return equals;
|
||||||
|
} catch (NoSuchAlgorithmException ex) {
|
||||||
|
Logger.printException(() -> "buildFieldEqualsHash failure", ex); // Will never happen.
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package app.revanced.extension.shared.checks;
|
||||||
|
|
||||||
|
// Fields are set by the patch. Do not modify.
|
||||||
|
// Fields are not final, because the compiler is inlining them.
|
||||||
|
final class PatchInfo {
|
||||||
|
static long PATCH_TIME = 0L;
|
||||||
|
|
||||||
|
final static class Build {
|
||||||
|
static String PATCH_BOARD = "";
|
||||||
|
static String PATCH_BOOTLOADER = "";
|
||||||
|
static String PATCH_BRAND = "";
|
||||||
|
static String PATCH_CPU_ABI = "";
|
||||||
|
static String PATCH_CPU_ABI2 = "";
|
||||||
|
static String PATCH_DEVICE = "";
|
||||||
|
static String PATCH_DISPLAY = "";
|
||||||
|
static String PATCH_FINGERPRINT = "";
|
||||||
|
static String PATCH_HARDWARE = "";
|
||||||
|
static String PATCH_HOST = "";
|
||||||
|
static String PATCH_ID = "";
|
||||||
|
static String PATCH_MANUFACTURER = "";
|
||||||
|
static String PATCH_MODEL = "";
|
||||||
|
static String PATCH_PRODUCT = "";
|
||||||
|
static String PATCH_RADIO = "";
|
||||||
|
static String PATCH_TAGS = "";
|
||||||
|
static String PATCH_TYPE = "";
|
||||||
|
static String PATCH_USER = "";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,208 @@
|
|||||||
|
package app.revanced.extension.shared.fixes.slink;
|
||||||
|
|
||||||
|
|
||||||
|
import android.app.Activity;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.net.Uri;
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.SocketTimeoutException;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.Utils.getContext;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class to implement /s/ link resolution in 3rd party Reddit apps.
|
||||||
|
* <br>
|
||||||
|
* <br>
|
||||||
|
* Usage:
|
||||||
|
* <br>
|
||||||
|
* <br>
|
||||||
|
* An implementation of this class must have two static methods that are called by the app:
|
||||||
|
* <ul>
|
||||||
|
* <li>public static boolean patchResolveSLink(String link)</li>
|
||||||
|
* <li>public static void patchSetAccessToken(String accessToken)</li>
|
||||||
|
* </ul>
|
||||||
|
* The static methods must call the instance methods of the base class.
|
||||||
|
* <br>
|
||||||
|
* The singleton pattern can be used to access the instance of the class:
|
||||||
|
* <pre>
|
||||||
|
* {@code
|
||||||
|
* {
|
||||||
|
* INSTANCE = new FixSLinksPatch();
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* </pre>
|
||||||
|
* Set the app's web view activity class as a fallback to open /s/ links if the resolution fails:
|
||||||
|
* <pre>
|
||||||
|
* {@code
|
||||||
|
* private FixSLinksPatch() {
|
||||||
|
* webViewActivityClass = WebViewActivity.class;
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* </pre>
|
||||||
|
* Hook the app's navigation handler to call this method before doing any of its own resolution:
|
||||||
|
* <pre>
|
||||||
|
* {@code
|
||||||
|
* public static boolean patchResolveSLink(Context context, String link) {
|
||||||
|
* return INSTANCE.resolveSLink(context, link);
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* </pre>
|
||||||
|
* If this method returns true, the app should early return and not do any of its own resolution.
|
||||||
|
* <br>
|
||||||
|
* <br>
|
||||||
|
* Hook the app's access token so that this class can use it to resolve /s/ links:
|
||||||
|
* <pre>
|
||||||
|
* {@code
|
||||||
|
* public static void patchSetAccessToken(String accessToken) {
|
||||||
|
* INSTANCE.setAccessToken(access_token);
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* </pre>
|
||||||
|
*/
|
||||||
|
public abstract class BaseFixSLinksPatch {
|
||||||
|
/**
|
||||||
|
* The class of the activity used to open links in a web view if resolving them fails.
|
||||||
|
*/
|
||||||
|
protected Class<? extends Activity> webViewActivityClass;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The access token used to resolve the /s/ link.
|
||||||
|
*/
|
||||||
|
protected String accessToken;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The URL that was trying to be resolved before the access token was set.
|
||||||
|
* If this is not null, the URL will be resolved right after the access token is set.
|
||||||
|
*/
|
||||||
|
protected String pendingUrl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The singleton instance of the class.
|
||||||
|
*/
|
||||||
|
protected static BaseFixSLinksPatch INSTANCE;
|
||||||
|
|
||||||
|
public boolean resolveSLink(String link) {
|
||||||
|
switch (resolveLink(link)) {
|
||||||
|
case ACCESS_TOKEN_START: {
|
||||||
|
pendingUrl = link;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case DO_NOTHING:
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResolveResult resolveLink(String link) {
|
||||||
|
Context context = getContext();
|
||||||
|
if (link.matches(".*reddit\\.com/r/[^/]+/s/[^/]+")) {
|
||||||
|
// A link ends with #bypass if it failed to resolve below.
|
||||||
|
// resolveLink is called with the same link again but this time with #bypass
|
||||||
|
// so that the link is opened in the app browser instead of trying to resolve it again.
|
||||||
|
if (link.endsWith("#bypass")) {
|
||||||
|
openInAppBrowser(context, link);
|
||||||
|
|
||||||
|
return ResolveResult.DO_NOTHING;
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.printDebug(() -> "Resolving " + link);
|
||||||
|
|
||||||
|
if (accessToken == null) {
|
||||||
|
// This is not optimal.
|
||||||
|
// However, an accessToken is necessary to make an authenticated request to Reddit.
|
||||||
|
// in case Reddit has banned the IP - e.g. VPN.
|
||||||
|
Intent startIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
|
||||||
|
context.startActivity(startIntent);
|
||||||
|
|
||||||
|
return ResolveResult.ACCESS_TOKEN_START;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Utils.runOnBackgroundThread(() -> {
|
||||||
|
String bypassLink = link + "#bypass";
|
||||||
|
|
||||||
|
String finalLocation = bypassLink;
|
||||||
|
try {
|
||||||
|
HttpURLConnection connection = getHttpURLConnection(link, accessToken);
|
||||||
|
connection.connect();
|
||||||
|
String location = connection.getHeaderField("location");
|
||||||
|
connection.disconnect();
|
||||||
|
|
||||||
|
Objects.requireNonNull(location, "Location is null");
|
||||||
|
|
||||||
|
finalLocation = location;
|
||||||
|
Logger.printDebug(() -> "Resolved " + link + " to " + location);
|
||||||
|
} catch (SocketTimeoutException e) {
|
||||||
|
Logger.printException(() -> "Timeout when trying to resolve " + link, e);
|
||||||
|
finalLocation = bypassLink;
|
||||||
|
} catch (Exception e) {
|
||||||
|
Logger.printException(() -> "Failed to resolve " + link, e);
|
||||||
|
finalLocation = bypassLink;
|
||||||
|
} finally {
|
||||||
|
Intent startIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(finalLocation));
|
||||||
|
startIntent.setPackage(context.getPackageName());
|
||||||
|
startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||||
|
context.startActivity(startIntent);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return ResolveResult.DO_NOTHING;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResolveResult.CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAccessToken(String accessToken) {
|
||||||
|
Logger.printDebug(() -> "Setting access token");
|
||||||
|
|
||||||
|
this.accessToken = accessToken;
|
||||||
|
|
||||||
|
// In case a link was trying to be resolved before access token was set.
|
||||||
|
// The link is resolved now, after the access token is set.
|
||||||
|
if (pendingUrl != null) {
|
||||||
|
String link = pendingUrl;
|
||||||
|
pendingUrl = null;
|
||||||
|
|
||||||
|
Logger.printDebug(() -> "Opening pending URL");
|
||||||
|
|
||||||
|
resolveLink(link);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void openInAppBrowser(Context context, String link) {
|
||||||
|
Intent intent = new Intent(context, webViewActivityClass);
|
||||||
|
intent.putExtra("url", link);
|
||||||
|
context.startActivity(intent);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
private HttpURLConnection getHttpURLConnection(String link, String accessToken) throws IOException {
|
||||||
|
URL url = new URL(link);
|
||||||
|
|
||||||
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||||
|
connection.setInstanceFollowRedirects(false);
|
||||||
|
connection.setRequestMethod("HEAD");
|
||||||
|
connection.setConnectTimeout(2000);
|
||||||
|
connection.setReadTimeout(2000);
|
||||||
|
|
||||||
|
if (accessToken != null) {
|
||||||
|
Logger.printDebug(() -> "Setting access token to make /s/ request");
|
||||||
|
|
||||||
|
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
|
||||||
|
} else {
|
||||||
|
Logger.printDebug(() -> "Not setting access token to make /s/ request, because it is null");
|
||||||
|
}
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package app.revanced.extension.shared.fixes.slink;
|
||||||
|
|
||||||
|
public enum ResolveResult {
|
||||||
|
// Let app handle rest of stuff
|
||||||
|
CONTINUE,
|
||||||
|
// Start app, to make it cache its access_token
|
||||||
|
ACCESS_TOKEN_START,
|
||||||
|
// Don't do anything - we started resolving
|
||||||
|
DO_NOTHING
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package app.revanced.extension.shared.settings;
|
||||||
|
|
||||||
|
import static java.lang.Boolean.FALSE;
|
||||||
|
import static java.lang.Boolean.TRUE;
|
||||||
|
import static app.revanced.extension.shared.settings.Setting.parent;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings shared across multiple apps.
|
||||||
|
*
|
||||||
|
* To ensure this class is loaded when the UI is created, app specific setting bundles should extend
|
||||||
|
* or reference this class.
|
||||||
|
*/
|
||||||
|
public class BaseSettings {
|
||||||
|
public static final BooleanSetting DEBUG = new BooleanSetting("revanced_debug", FALSE);
|
||||||
|
public static final BooleanSetting DEBUG_STACKTRACE = new BooleanSetting("revanced_debug_stacktrace", FALSE, parent(DEBUG));
|
||||||
|
public static final BooleanSetting DEBUG_TOAST_ON_ERROR = new BooleanSetting("revanced_debug_toast_on_error", TRUE, "revanced_debug_toast_on_error_user_dialog_message");
|
||||||
|
}
|
@ -0,0 +1,79 @@
|
|||||||
|
package app.revanced.extension.shared.settings;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import org.json.JSONException;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class BooleanSetting extends Setting<Boolean> {
|
||||||
|
public BooleanSetting(String key, Boolean defaultValue) {
|
||||||
|
super(key, defaultValue);
|
||||||
|
}
|
||||||
|
public BooleanSetting(String key, Boolean defaultValue, boolean rebootApp) {
|
||||||
|
super(key, defaultValue, rebootApp);
|
||||||
|
}
|
||||||
|
public BooleanSetting(String key, Boolean defaultValue, boolean rebootApp, boolean includeWithImportExport) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport);
|
||||||
|
}
|
||||||
|
public BooleanSetting(String key, Boolean defaultValue, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, userDialogMessage);
|
||||||
|
}
|
||||||
|
public BooleanSetting(String key, Boolean defaultValue, Availability availability) {
|
||||||
|
super(key, defaultValue, availability);
|
||||||
|
}
|
||||||
|
public BooleanSetting(String key, Boolean defaultValue, boolean rebootApp, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage);
|
||||||
|
}
|
||||||
|
public BooleanSetting(String key, Boolean defaultValue, boolean rebootApp, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, availability);
|
||||||
|
}
|
||||||
|
public BooleanSetting(String key, Boolean defaultValue, boolean rebootApp, String userDialogMessage, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
public BooleanSetting(@NonNull String key, @NonNull Boolean defaultValue, boolean rebootApp, boolean includeWithImportExport, @Nullable String userDialogMessage, @Nullable Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets, but does _not_ persistently save the value.
|
||||||
|
* This method is only to be used by the Settings preference code.
|
||||||
|
*
|
||||||
|
* This intentionally is a static method to deter
|
||||||
|
* accidental usage when {@link #save(Boolean)} was intnded.
|
||||||
|
*/
|
||||||
|
public static void privateSetValue(@NonNull BooleanSetting setting, @NonNull Boolean newValue) {
|
||||||
|
setting.value = Objects.requireNonNull(newValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void load() {
|
||||||
|
value = preferences.getBoolean(key, defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Boolean readFromJSON(JSONObject json, String importExportKey) throws JSONException {
|
||||||
|
return json.getBoolean(importExportKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void setValueFromString(@NonNull String newValue) {
|
||||||
|
value = Boolean.valueOf(Objects.requireNonNull(newValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void save(@NonNull Boolean newValue) {
|
||||||
|
// Must set before saving to preferences (otherwise importing fails to update UI correctly).
|
||||||
|
value = Objects.requireNonNull(newValue);
|
||||||
|
preferences.saveBoolean(key, newValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
public Boolean get() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,117 @@
|
|||||||
|
package app.revanced.extension.shared.settings;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import org.json.JSONException;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If an Enum value is removed or changed, any saved or imported data using the
|
||||||
|
* non-existent value will be reverted to the default value
|
||||||
|
* (the event is logged, but no user error is displayed).
|
||||||
|
*
|
||||||
|
* All saved JSON text is converted to lowercase to keep the output less obnoxious.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class EnumSetting<T extends Enum<?>> extends Setting<T> {
|
||||||
|
public EnumSetting(String key, T defaultValue) {
|
||||||
|
super(key, defaultValue);
|
||||||
|
}
|
||||||
|
public EnumSetting(String key, T defaultValue, boolean rebootApp) {
|
||||||
|
super(key, defaultValue, rebootApp);
|
||||||
|
}
|
||||||
|
public EnumSetting(String key, T defaultValue, boolean rebootApp, boolean includeWithImportExport) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport);
|
||||||
|
}
|
||||||
|
public EnumSetting(String key, T defaultValue, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, userDialogMessage);
|
||||||
|
}
|
||||||
|
public EnumSetting(String key, T defaultValue, Availability availability) {
|
||||||
|
super(key, defaultValue, availability);
|
||||||
|
}
|
||||||
|
public EnumSetting(String key, T defaultValue, boolean rebootApp, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage);
|
||||||
|
}
|
||||||
|
public EnumSetting(String key, T defaultValue, boolean rebootApp, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, availability);
|
||||||
|
}
|
||||||
|
public EnumSetting(String key, T defaultValue, boolean rebootApp, String userDialogMessage, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
public EnumSetting(@NonNull String key, @NonNull T defaultValue, boolean rebootApp, boolean includeWithImportExport, @Nullable String userDialogMessage, @Nullable Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void load() {
|
||||||
|
value = preferences.getEnum(key, defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected T readFromJSON(JSONObject json, String importExportKey) throws JSONException {
|
||||||
|
String enumName = json.getString(importExportKey);
|
||||||
|
try {
|
||||||
|
return getEnumFromString(enumName);
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
// Info level to allow removing enum values in the future without showing any user errors.
|
||||||
|
Logger.printInfo(() -> "Using default, and ignoring unknown enum value: " + enumName, ex);
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void writeToJSON(JSONObject json, String importExportKey) throws JSONException {
|
||||||
|
// Use lowercase to keep the output less ugly.
|
||||||
|
json.put(importExportKey, value.name().toLowerCase(Locale.ENGLISH));
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
private T getEnumFromString(String enumName) {
|
||||||
|
//noinspection ConstantConditions
|
||||||
|
for (Enum<?> value : defaultValue.getClass().getEnumConstants()) {
|
||||||
|
if (value.name().equalsIgnoreCase(enumName)) {
|
||||||
|
// noinspection unchecked
|
||||||
|
return (T) value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("Unknown enum value: " + enumName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void setValueFromString(@NonNull String newValue) {
|
||||||
|
value = getEnumFromString(Objects.requireNonNull(newValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void save(@NonNull T newValue) {
|
||||||
|
// Must set before saving to preferences (otherwise importing fails to update UI correctly).
|
||||||
|
value = Objects.requireNonNull(newValue);
|
||||||
|
preferences.saveEnumAsString(key, newValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
public T get() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Availability based on if this setting is currently set to any of the provided types.
|
||||||
|
*/
|
||||||
|
@SafeVarargs
|
||||||
|
public final Setting.Availability availability(@NonNull T... types) {
|
||||||
|
return () -> {
|
||||||
|
T currentEnumType = get();
|
||||||
|
for (T enumType : types) {
|
||||||
|
if (currentEnumType == enumType) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,69 @@
|
|||||||
|
package app.revanced.extension.shared.settings;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import org.json.JSONException;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class FloatSetting extends Setting<Float> {
|
||||||
|
|
||||||
|
public FloatSetting(String key, Float defaultValue) {
|
||||||
|
super(key, defaultValue);
|
||||||
|
}
|
||||||
|
public FloatSetting(String key, Float defaultValue, boolean rebootApp) {
|
||||||
|
super(key, defaultValue, rebootApp);
|
||||||
|
}
|
||||||
|
public FloatSetting(String key, Float defaultValue, boolean rebootApp, boolean includeWithImportExport) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport);
|
||||||
|
}
|
||||||
|
public FloatSetting(String key, Float defaultValue, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, userDialogMessage);
|
||||||
|
}
|
||||||
|
public FloatSetting(String key, Float defaultValue, Availability availability) {
|
||||||
|
super(key, defaultValue, availability);
|
||||||
|
}
|
||||||
|
public FloatSetting(String key, Float defaultValue, boolean rebootApp, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage);
|
||||||
|
}
|
||||||
|
public FloatSetting(String key, Float defaultValue, boolean rebootApp, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, availability);
|
||||||
|
}
|
||||||
|
public FloatSetting(String key, Float defaultValue, boolean rebootApp, String userDialogMessage, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
public FloatSetting(@NonNull String key, @NonNull Float defaultValue, boolean rebootApp, boolean includeWithImportExport, @Nullable String userDialogMessage, @Nullable Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void load() {
|
||||||
|
value = preferences.getFloatString(key, defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Float readFromJSON(JSONObject json, String importExportKey) throws JSONException {
|
||||||
|
return (float) json.getDouble(importExportKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void setValueFromString(@NonNull String newValue) {
|
||||||
|
value = Float.valueOf(Objects.requireNonNull(newValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void save(@NonNull Float newValue) {
|
||||||
|
// Must set before saving to preferences (otherwise importing fails to update UI correctly).
|
||||||
|
value = Objects.requireNonNull(newValue);
|
||||||
|
preferences.saveFloatString(key, newValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
public Float get() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,69 @@
|
|||||||
|
package app.revanced.extension.shared.settings;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import org.json.JSONException;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class IntegerSetting extends Setting<Integer> {
|
||||||
|
|
||||||
|
public IntegerSetting(String key, Integer defaultValue) {
|
||||||
|
super(key, defaultValue);
|
||||||
|
}
|
||||||
|
public IntegerSetting(String key, Integer defaultValue, boolean rebootApp) {
|
||||||
|
super(key, defaultValue, rebootApp);
|
||||||
|
}
|
||||||
|
public IntegerSetting(String key, Integer defaultValue, boolean rebootApp, boolean includeWithImportExport) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport);
|
||||||
|
}
|
||||||
|
public IntegerSetting(String key, Integer defaultValue, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, userDialogMessage);
|
||||||
|
}
|
||||||
|
public IntegerSetting(String key, Integer defaultValue, Availability availability) {
|
||||||
|
super(key, defaultValue, availability);
|
||||||
|
}
|
||||||
|
public IntegerSetting(String key, Integer defaultValue, boolean rebootApp, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage);
|
||||||
|
}
|
||||||
|
public IntegerSetting(String key, Integer defaultValue, boolean rebootApp, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, availability);
|
||||||
|
}
|
||||||
|
public IntegerSetting(String key, Integer defaultValue, boolean rebootApp, String userDialogMessage, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
public IntegerSetting(@NonNull String key, @NonNull Integer defaultValue, boolean rebootApp, boolean includeWithImportExport, @Nullable String userDialogMessage, @Nullable Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void load() {
|
||||||
|
value = preferences.getIntegerString(key, defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Integer readFromJSON(JSONObject json, String importExportKey) throws JSONException {
|
||||||
|
return json.getInt(importExportKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void setValueFromString(@NonNull String newValue) {
|
||||||
|
value = Integer.valueOf(Objects.requireNonNull(newValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void save(@NonNull Integer newValue) {
|
||||||
|
// Must set before saving to preferences (otherwise importing fails to update UI correctly).
|
||||||
|
value = Objects.requireNonNull(newValue);
|
||||||
|
preferences.saveIntegerString(key, newValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
public Integer get() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,69 @@
|
|||||||
|
package app.revanced.extension.shared.settings;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import org.json.JSONException;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class LongSetting extends Setting<Long> {
|
||||||
|
|
||||||
|
public LongSetting(String key, Long defaultValue) {
|
||||||
|
super(key, defaultValue);
|
||||||
|
}
|
||||||
|
public LongSetting(String key, Long defaultValue, boolean rebootApp) {
|
||||||
|
super(key, defaultValue, rebootApp);
|
||||||
|
}
|
||||||
|
public LongSetting(String key, Long defaultValue, boolean rebootApp, boolean includeWithImportExport) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport);
|
||||||
|
}
|
||||||
|
public LongSetting(String key, Long defaultValue, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, userDialogMessage);
|
||||||
|
}
|
||||||
|
public LongSetting(String key, Long defaultValue, Availability availability) {
|
||||||
|
super(key, defaultValue, availability);
|
||||||
|
}
|
||||||
|
public LongSetting(String key, Long defaultValue, boolean rebootApp, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage);
|
||||||
|
}
|
||||||
|
public LongSetting(String key, Long defaultValue, boolean rebootApp, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, availability);
|
||||||
|
}
|
||||||
|
public LongSetting(String key, Long defaultValue, boolean rebootApp, String userDialogMessage, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
public LongSetting(@NonNull String key, @NonNull Long defaultValue, boolean rebootApp, boolean includeWithImportExport, @Nullable String userDialogMessage, @Nullable Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void load() {
|
||||||
|
value = preferences.getLongString(key, defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Long readFromJSON(JSONObject json, String importExportKey) throws JSONException {
|
||||||
|
return json.getLong(importExportKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void setValueFromString(@NonNull String newValue) {
|
||||||
|
value = Long.valueOf(Objects.requireNonNull(newValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void save(@NonNull Long newValue) {
|
||||||
|
// Must set before saving to preferences (otherwise importing fails to update UI correctly).
|
||||||
|
value = Objects.requireNonNull(newValue);
|
||||||
|
preferences.saveLongString(key, newValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
public Long get() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,437 @@
|
|||||||
|
package app.revanced.extension.shared.settings;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.StringRef;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
import app.revanced.extension.shared.settings.preference.SharedPrefCategory;
|
||||||
|
import app.revanced.extension.youtube.sponsorblock.SponsorBlockSettings;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.json.JSONException;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public abstract class Setting<T> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates if a {@link Setting} is available to edit and use.
|
||||||
|
* Typically this is dependent upon other BooleanSetting(s) set to 'true',
|
||||||
|
* but this can be used to call into extension code and check other conditions.
|
||||||
|
*/
|
||||||
|
public interface Availability {
|
||||||
|
boolean isAvailable();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Availability based on a single parent setting being enabled.
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public static Availability parent(@NonNull BooleanSetting parent) {
|
||||||
|
return parent::get;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Availability based on all parents being enabled.
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public static Availability parentsAll(@NonNull BooleanSetting... parents) {
|
||||||
|
return () -> {
|
||||||
|
for (BooleanSetting parent : parents) {
|
||||||
|
if (!parent.get()) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Availability based on any parent being enabled.
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public static Availability parentsAny(@NonNull BooleanSetting... parents) {
|
||||||
|
return () -> {
|
||||||
|
for (BooleanSetting parent : parents) {
|
||||||
|
if (parent.get()) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* All settings that were instantiated.
|
||||||
|
* When a new setting is created, it is automatically added to this list.
|
||||||
|
*/
|
||||||
|
private static final List<Setting<?>> SETTINGS = new ArrayList<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map of setting path to setting object.
|
||||||
|
*/
|
||||||
|
private static final Map<String, Setting<?>> PATH_TO_SETTINGS = new HashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Preference all instances are saved to.
|
||||||
|
*/
|
||||||
|
public static final SharedPrefCategory preferences = new SharedPrefCategory("revanced_prefs");
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
public static Setting<?> getSettingFromPath(@NonNull String str) {
|
||||||
|
return PATH_TO_SETTINGS.get(str);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return All settings that have been created.
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public static List<Setting<?>> allLoadedSettings() {
|
||||||
|
return Collections.unmodifiableList(SETTINGS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return All settings that have been created, sorted by keys.
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
private static List<Setting<?>> allLoadedSettingsSorted() {
|
||||||
|
Collections.sort(SETTINGS, (Setting<?> o1, Setting<?> o2) -> o1.key.compareTo(o2.key));
|
||||||
|
return allLoadedSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The key used to store the value in the shared preferences.
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public final String key;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The default value of the setting.
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
public final T defaultValue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the app should be rebooted, if this setting is changed
|
||||||
|
*/
|
||||||
|
public final boolean rebootApp;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If this setting should be included when importing/exporting settings.
|
||||||
|
*/
|
||||||
|
public final boolean includeWithImportExport;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If this setting is available to edit and use.
|
||||||
|
* Not to be confused with it's status returned from {@link #get()}.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private final Availability availability;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Confirmation message to display, if the user tries to change the setting from the default value.
|
||||||
|
* Currently this works only for Boolean setting types.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
public final StringRef userDialogMessage;
|
||||||
|
|
||||||
|
// Must be volatile, as some settings are read/write from different threads.
|
||||||
|
// Of note, the object value is persistently stored using SharedPreferences (which is thread safe).
|
||||||
|
/**
|
||||||
|
* The value of the setting.
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
protected volatile T value;
|
||||||
|
|
||||||
|
public Setting(String key, T defaultValue) {
|
||||||
|
this(key, defaultValue, false, true, null, null);
|
||||||
|
}
|
||||||
|
public Setting(String key, T defaultValue, boolean rebootApp) {
|
||||||
|
this(key, defaultValue, rebootApp, true, null, null);
|
||||||
|
}
|
||||||
|
public Setting(String key, T defaultValue, boolean rebootApp, boolean includeWithImportExport) {
|
||||||
|
this(key, defaultValue, rebootApp, includeWithImportExport, null, null);
|
||||||
|
}
|
||||||
|
public Setting(String key, T defaultValue, String userDialogMessage) {
|
||||||
|
this(key, defaultValue, false, true, userDialogMessage, null);
|
||||||
|
}
|
||||||
|
public Setting(String key, T defaultValue, Availability availability) {
|
||||||
|
this(key, defaultValue, false, true, null, availability);
|
||||||
|
}
|
||||||
|
public Setting(String key, T defaultValue, boolean rebootApp, String userDialogMessage) {
|
||||||
|
this(key, defaultValue, rebootApp, true, userDialogMessage, null);
|
||||||
|
}
|
||||||
|
public Setting(String key, T defaultValue, boolean rebootApp, Availability availability) {
|
||||||
|
this(key, defaultValue, rebootApp, true, null, availability);
|
||||||
|
}
|
||||||
|
public Setting(String key, T defaultValue, boolean rebootApp, String userDialogMessage, Availability availability) {
|
||||||
|
this(key, defaultValue, rebootApp, true, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A setting backed by a shared preference.
|
||||||
|
*
|
||||||
|
* @param key The key used to store the value in the shared preferences.
|
||||||
|
* @param defaultValue The default value of the setting.
|
||||||
|
* @param rebootApp If the app should be rebooted, if this setting is changed.
|
||||||
|
* @param includeWithImportExport If this setting should be shown in the import/export dialog.
|
||||||
|
* @param userDialogMessage Confirmation message to display, if the user tries to change the setting from the default value.
|
||||||
|
* @param availability Condition that must be true, for this setting to be available to configure.
|
||||||
|
*/
|
||||||
|
public Setting(@NonNull String key,
|
||||||
|
@NonNull T defaultValue,
|
||||||
|
boolean rebootApp,
|
||||||
|
boolean includeWithImportExport,
|
||||||
|
@Nullable String userDialogMessage,
|
||||||
|
@Nullable Availability availability
|
||||||
|
) {
|
||||||
|
this.key = Objects.requireNonNull(key);
|
||||||
|
this.value = this.defaultValue = Objects.requireNonNull(defaultValue);
|
||||||
|
this.rebootApp = rebootApp;
|
||||||
|
this.includeWithImportExport = includeWithImportExport;
|
||||||
|
this.userDialogMessage = (userDialogMessage == null) ? null : new StringRef(userDialogMessage);
|
||||||
|
this.availability = availability;
|
||||||
|
|
||||||
|
SETTINGS.add(this);
|
||||||
|
if (PATH_TO_SETTINGS.put(key, this) != null) {
|
||||||
|
// Debug setting may not be created yet so using Logger may cause an initialization crash.
|
||||||
|
// Show a toast instead.
|
||||||
|
Utils.showToastLong(this.getClass().getSimpleName()
|
||||||
|
+ " error: Duplicate Setting key found: " + key);
|
||||||
|
}
|
||||||
|
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Migrate a setting value if the path is renamed but otherwise the old and new settings are identical.
|
||||||
|
*/
|
||||||
|
public static <T> void migrateOldSettingToNew(@NonNull Setting<T> oldSetting, @NonNull Setting<T> newSetting) {
|
||||||
|
if (oldSetting == newSetting) throw new IllegalArgumentException();
|
||||||
|
|
||||||
|
if (!oldSetting.isSetToDefault()) {
|
||||||
|
Logger.printInfo(() -> "Migrating old setting value: " + oldSetting + " into replacement setting: " + newSetting);
|
||||||
|
newSetting.save(oldSetting.value);
|
||||||
|
oldSetting.resetToDefault();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Migrate an old Setting value previously stored in a different SharedPreference.
|
||||||
|
*
|
||||||
|
* This method will be deleted in the future.
|
||||||
|
*/
|
||||||
|
public static void migrateFromOldPreferences(@NonNull SharedPrefCategory oldPrefs, @NonNull Setting setting, String settingKey) {
|
||||||
|
if (!oldPrefs.preferences.contains(settingKey)) {
|
||||||
|
return; // Nothing to do.
|
||||||
|
}
|
||||||
|
|
||||||
|
Object newValue = setting.get();
|
||||||
|
final Object migratedValue;
|
||||||
|
if (setting instanceof BooleanSetting) {
|
||||||
|
migratedValue = oldPrefs.getBoolean(settingKey, (Boolean) newValue);
|
||||||
|
} else if (setting instanceof IntegerSetting) {
|
||||||
|
migratedValue = oldPrefs.getIntegerString(settingKey, (Integer) newValue);
|
||||||
|
} else if (setting instanceof LongSetting) {
|
||||||
|
migratedValue = oldPrefs.getLongString(settingKey, (Long) newValue);
|
||||||
|
} else if (setting instanceof FloatSetting) {
|
||||||
|
migratedValue = oldPrefs.getFloatString(settingKey, (Float) newValue);
|
||||||
|
} else if (setting instanceof StringSetting) {
|
||||||
|
migratedValue = oldPrefs.getString(settingKey, (String) newValue);
|
||||||
|
} else {
|
||||||
|
Logger.printException(() -> "Unknown setting: " + setting);
|
||||||
|
// Remove otherwise it'll show a toast on every launch
|
||||||
|
oldPrefs.preferences.edit().remove(settingKey).apply();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
oldPrefs.preferences.edit().remove(settingKey).apply(); // Remove the old setting.
|
||||||
|
if (migratedValue.equals(newValue)) {
|
||||||
|
Logger.printDebug(() -> "Value does not need migrating: " + settingKey);
|
||||||
|
return; // Old value is already equal to the new setting value.
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.printDebug(() -> "Migrating old preference value into current preference: " + settingKey);
|
||||||
|
//noinspection unchecked
|
||||||
|
setting.save(migratedValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets, but does _not_ persistently save the value.
|
||||||
|
* This method is only to be used by the Settings preference code.
|
||||||
|
*
|
||||||
|
* This intentionally is a static method to deter
|
||||||
|
* accidental usage when {@link #save(Object)} was intended.
|
||||||
|
*/
|
||||||
|
public static void privateSetValueFromString(@NonNull Setting<?> setting, @NonNull String newValue) {
|
||||||
|
setting.setValueFromString(newValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the value of {@link #value}, but do not save to {@link #preferences}.
|
||||||
|
*/
|
||||||
|
protected abstract void setValueFromString(@NonNull String newValue);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load and set the value of {@link #value}.
|
||||||
|
*/
|
||||||
|
protected abstract void load();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persistently saves the value.
|
||||||
|
*/
|
||||||
|
public abstract void save(@NonNull T newValue);
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
public abstract T get();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Identical to calling {@link #save(Object)} using {@link #defaultValue}.
|
||||||
|
*/
|
||||||
|
public void resetToDefault() {
|
||||||
|
save(defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return if this setting can be configured and used.
|
||||||
|
*/
|
||||||
|
public boolean isAvailable() {
|
||||||
|
return availability == null || availability.isAvailable();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return if the currently set value is the same as {@link #defaultValue}
|
||||||
|
*/
|
||||||
|
public boolean isSetToDefault() {
|
||||||
|
return value.equals(defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return key + "=" + get();
|
||||||
|
}
|
||||||
|
|
||||||
|
// region Import / export
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If a setting path has this prefix, then remove it before importing/exporting.
|
||||||
|
*/
|
||||||
|
private static final String OPTIONAL_REVANCED_SETTINGS_PREFIX = "revanced_";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The path, minus any 'revanced' prefix to keep json concise.
|
||||||
|
*/
|
||||||
|
private String getImportExportKey() {
|
||||||
|
if (key.startsWith(OPTIONAL_REVANCED_SETTINGS_PREFIX)) {
|
||||||
|
return key.substring(OPTIONAL_REVANCED_SETTINGS_PREFIX.length());
|
||||||
|
}
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param importExportKey The JSON key. The JSONObject parameter will contain data for this key.
|
||||||
|
* @return the value stored using the import/export key. Do not set any values in this method.
|
||||||
|
*/
|
||||||
|
protected abstract T readFromJSON(JSONObject json, String importExportKey) throws JSONException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves this instance to JSON.
|
||||||
|
* <p>
|
||||||
|
* To keep the JSON simple and readable,
|
||||||
|
* subclasses should not write out any embedded types (such as JSON Array or Dictionaries).
|
||||||
|
* <p>
|
||||||
|
* If this instance is not a type supported natively by JSON (ie: it's not a String/Integer/Float/Long),
|
||||||
|
* then subclasses can override this method and write out a String value representing the value.
|
||||||
|
*/
|
||||||
|
protected void writeToJSON(JSONObject json, String importExportKey) throws JSONException {
|
||||||
|
json.put(importExportKey, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
public static String exportToJson(@Nullable Context alertDialogContext) {
|
||||||
|
try {
|
||||||
|
JSONObject json = new JSONObject();
|
||||||
|
for (Setting<?> setting : allLoadedSettingsSorted()) {
|
||||||
|
String importExportKey = setting.getImportExportKey();
|
||||||
|
if (json.has(importExportKey)) {
|
||||||
|
throw new IllegalArgumentException("duplicate key found: " + importExportKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
final boolean exportDefaultValues = false; // Enable to see what all settings looks like in the UI.
|
||||||
|
//noinspection ConstantValue
|
||||||
|
if (setting.includeWithImportExport && (!setting.isSetToDefault() || exportDefaultValues)) {
|
||||||
|
setting.writeToJSON(json, importExportKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SponsorBlockSettings.showExportWarningIfNeeded(alertDialogContext);
|
||||||
|
|
||||||
|
if (json.length() == 0) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
String export = json.toString(0);
|
||||||
|
|
||||||
|
// Remove the outer JSON braces to make the output more compact,
|
||||||
|
// and leave less chance of the user forgetting to copy it
|
||||||
|
return export.substring(2, export.length() - 2);
|
||||||
|
} catch (JSONException e) {
|
||||||
|
Logger.printException(() -> "Export failure", e); // should never happen
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return if any settings that require a reboot were changed.
|
||||||
|
*/
|
||||||
|
public static boolean importFromJSON(@NonNull String settingsJsonString) {
|
||||||
|
try {
|
||||||
|
if (!settingsJsonString.matches("[\\s\\S]*\\{")) {
|
||||||
|
settingsJsonString = '{' + settingsJsonString + '}'; // Restore outer JSON braces
|
||||||
|
}
|
||||||
|
JSONObject json = new JSONObject(settingsJsonString);
|
||||||
|
|
||||||
|
boolean rebootSettingChanged = false;
|
||||||
|
int numberOfSettingsImported = 0;
|
||||||
|
for (Setting setting : SETTINGS) {
|
||||||
|
String key = setting.getImportExportKey();
|
||||||
|
if (json.has(key)) {
|
||||||
|
Object value = setting.readFromJSON(json, key);
|
||||||
|
if (!setting.get().equals(value)) {
|
||||||
|
rebootSettingChanged |= setting.rebootApp;
|
||||||
|
//noinspection unchecked
|
||||||
|
setting.save(value);
|
||||||
|
}
|
||||||
|
numberOfSettingsImported++;
|
||||||
|
} else if (setting.includeWithImportExport && !setting.isSetToDefault()) {
|
||||||
|
Logger.printDebug(() -> "Resetting to default: " + setting);
|
||||||
|
rebootSettingChanged |= setting.rebootApp;
|
||||||
|
setting.resetToDefault();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SB Enum categories are saved using StringSettings.
|
||||||
|
// Which means they need to reload again if changed by other code (such as here).
|
||||||
|
// This call could be removed by creating a custom Setting class that manages the
|
||||||
|
// "String <-> Enum" logic or by adding an event hook of when settings are imported.
|
||||||
|
// But for now this is simple and works.
|
||||||
|
SponsorBlockSettings.updateFromImportedSettings();
|
||||||
|
|
||||||
|
Utils.showToastLong(numberOfSettingsImported == 0
|
||||||
|
? str("revanced_settings_import_reset")
|
||||||
|
: str("revanced_settings_import_success", numberOfSettingsImported));
|
||||||
|
|
||||||
|
return rebootSettingChanged;
|
||||||
|
} catch (JSONException | IllegalArgumentException ex) {
|
||||||
|
Utils.showToastLong(str("revanced_settings_import_failure_parse", ex.getMessage()));
|
||||||
|
Logger.printInfo(() -> "", ex);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "Import failure: " + ex.getMessage(), ex); // should never happen
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// End import / export
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,69 @@
|
|||||||
|
package app.revanced.extension.shared.settings;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import org.json.JSONException;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class StringSetting extends Setting<String> {
|
||||||
|
|
||||||
|
public StringSetting(String key, String defaultValue) {
|
||||||
|
super(key, defaultValue);
|
||||||
|
}
|
||||||
|
public StringSetting(String key, String defaultValue, boolean rebootApp) {
|
||||||
|
super(key, defaultValue, rebootApp);
|
||||||
|
}
|
||||||
|
public StringSetting(String key, String defaultValue, boolean rebootApp, boolean includeWithImportExport) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport);
|
||||||
|
}
|
||||||
|
public StringSetting(String key, String defaultValue, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, userDialogMessage);
|
||||||
|
}
|
||||||
|
public StringSetting(String key, String defaultValue, Availability availability) {
|
||||||
|
super(key, defaultValue, availability);
|
||||||
|
}
|
||||||
|
public StringSetting(String key, String defaultValue, boolean rebootApp, String userDialogMessage) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage);
|
||||||
|
}
|
||||||
|
public StringSetting(String key, String defaultValue, boolean rebootApp, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, availability);
|
||||||
|
}
|
||||||
|
public StringSetting(String key, String defaultValue, boolean rebootApp, String userDialogMessage, Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
public StringSetting(@NonNull String key, @NonNull String defaultValue, boolean rebootApp, boolean includeWithImportExport, @Nullable String userDialogMessage, @Nullable Availability availability) {
|
||||||
|
super(key, defaultValue, rebootApp, includeWithImportExport, userDialogMessage, availability);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void load() {
|
||||||
|
value = preferences.getString(key, defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String readFromJSON(JSONObject json, String importExportKey) throws JSONException {
|
||||||
|
return json.getString(importExportKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void setValueFromString(@NonNull String newValue) {
|
||||||
|
value = Objects.requireNonNull(newValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void save(@NonNull String newValue) {
|
||||||
|
// Must set before saving to preferences (otherwise importing fails to update UI correctly).
|
||||||
|
value = Objects.requireNonNull(newValue);
|
||||||
|
preferences.saveString(key, newValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
public String get() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,274 @@
|
|||||||
|
package app.revanced.extension.shared.settings.preference;
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint;
|
||||||
|
import android.app.AlertDialog;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.SharedPreferences;
|
||||||
|
import android.os.Bundle;
|
||||||
|
import android.preference.*;
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
import app.revanced.extension.shared.settings.BaseSettings;
|
||||||
|
import app.revanced.extension.shared.settings.BooleanSetting;
|
||||||
|
import app.revanced.extension.shared.settings.Setting;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
|
||||||
|
@SuppressWarnings({"unused", "deprecation"})
|
||||||
|
public abstract class AbstractPreferenceFragment extends PreferenceFragment {
|
||||||
|
/**
|
||||||
|
* Indicates that if a preference changes,
|
||||||
|
* to apply the change from the Setting to the UI component.
|
||||||
|
*/
|
||||||
|
public static boolean settingImportInProgress;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Confirm and restart dialog button text and title.
|
||||||
|
* Set by subclasses if Strings cannot be added as a resource.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
protected static String restartDialogButtonText, restartDialogTitle, confirmDialogTitle;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Used to prevent showing reboot dialog, if user cancels a setting user dialog.
|
||||||
|
*/
|
||||||
|
private boolean showingUserDialogMessage;
|
||||||
|
|
||||||
|
private final SharedPreferences.OnSharedPreferenceChangeListener listener = (sharedPreferences, str) -> {
|
||||||
|
try {
|
||||||
|
Setting<?> setting = Setting.getSettingFromPath(str);
|
||||||
|
if (setting == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Preference pref = findPreference(str);
|
||||||
|
if (pref == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Logger.printDebug(() -> "Preference changed: " + setting.key);
|
||||||
|
|
||||||
|
// Apply 'Setting <- Preference', unless during importing when it needs to be 'Setting -> Preference'.
|
||||||
|
updatePreference(pref, setting, true, settingImportInProgress);
|
||||||
|
// Update any other preference availability that may now be different.
|
||||||
|
updateUIAvailability();
|
||||||
|
|
||||||
|
if (settingImportInProgress) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!showingUserDialogMessage) {
|
||||||
|
if (setting.userDialogMessage != null && ((SwitchPreference) pref).isChecked() != (Boolean) setting.defaultValue) {
|
||||||
|
showSettingUserDialogConfirmation((SwitchPreference) pref, (BooleanSetting) setting);
|
||||||
|
} else if (setting.rebootApp) {
|
||||||
|
showRestartDialog(getContext());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "OnSharedPreferenceChangeListener failure", ex);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize this instance, and do any custom behavior.
|
||||||
|
* <p>
|
||||||
|
* To ensure all {@link Setting} instances are correctly synced to the UI,
|
||||||
|
* it is important that subclasses make a call or otherwise reference their Settings class bundle
|
||||||
|
* so all app specific {@link Setting} instances are loaded before this method returns.
|
||||||
|
*/
|
||||||
|
protected void initialize() {
|
||||||
|
final var identifier = Utils.getResourceIdentifier("revanced_prefs", "xml");
|
||||||
|
|
||||||
|
if (identifier == 0) return;
|
||||||
|
addPreferencesFromResource(identifier);
|
||||||
|
Utils.sortPreferenceGroups(getPreferenceScreen());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void showSettingUserDialogConfirmation(SwitchPreference switchPref, BooleanSetting setting) {
|
||||||
|
Utils.verifyOnMainThread();
|
||||||
|
|
||||||
|
final var context = getContext();
|
||||||
|
if (confirmDialogTitle == null) {
|
||||||
|
confirmDialogTitle = str("revanced_settings_confirm_user_dialog_title");
|
||||||
|
}
|
||||||
|
showingUserDialogMessage = true;
|
||||||
|
new AlertDialog.Builder(context)
|
||||||
|
.setTitle(confirmDialogTitle)
|
||||||
|
.setMessage(setting.userDialogMessage.toString())
|
||||||
|
.setPositiveButton(android.R.string.ok, (dialog, id) -> {
|
||||||
|
if (setting.rebootApp) {
|
||||||
|
showRestartDialog(context);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.setNegativeButton(android.R.string.cancel, (dialog, id) -> {
|
||||||
|
switchPref.setChecked(setting.defaultValue); // Recursive call that resets the Setting value.
|
||||||
|
})
|
||||||
|
.setOnDismissListener(dialog -> {
|
||||||
|
showingUserDialogMessage = false;
|
||||||
|
})
|
||||||
|
.setCancelable(false)
|
||||||
|
.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates all Preferences values and their availability using the current values in {@link Setting}.
|
||||||
|
*/
|
||||||
|
protected void updateUIToSettingValues() {
|
||||||
|
updatePreferenceScreen(getPreferenceScreen(), true,true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates Preferences availability only using the status of {@link Setting}.
|
||||||
|
*/
|
||||||
|
protected void updateUIAvailability() {
|
||||||
|
updatePreferenceScreen(getPreferenceScreen(), false, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Syncs all UI Preferences to any {@link Setting} they represent.
|
||||||
|
*/
|
||||||
|
private void updatePreferenceScreen(@NonNull PreferenceScreen screen,
|
||||||
|
boolean syncSettingValue,
|
||||||
|
boolean applySettingToPreference) {
|
||||||
|
// Alternatively this could iterate thru all Settings and check for any matching Preferences,
|
||||||
|
// but there are many more Settings than UI preferences so it's more efficient to only check
|
||||||
|
// the Preferences.
|
||||||
|
for (int i = 0, prefCount = screen.getPreferenceCount(); i < prefCount; i++) {
|
||||||
|
Preference pref = screen.getPreference(i);
|
||||||
|
if (pref instanceof PreferenceScreen) {
|
||||||
|
updatePreferenceScreen((PreferenceScreen) pref, syncSettingValue, applySettingToPreference);
|
||||||
|
} else if (pref.hasKey()) {
|
||||||
|
String key = pref.getKey();
|
||||||
|
Setting<?> setting = Setting.getSettingFromPath(key);
|
||||||
|
|
||||||
|
if (setting != null) {
|
||||||
|
updatePreference(pref, setting, syncSettingValue, applySettingToPreference);
|
||||||
|
} else if (BaseSettings.DEBUG.get() && (pref instanceof SwitchPreference
|
||||||
|
|| pref instanceof EditTextPreference || pref instanceof ListPreference)) {
|
||||||
|
// Probably a typo in the patches preference declaration.
|
||||||
|
Logger.printException(() -> "Preference key has no setting: " + key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles syncing a UI Preference with the {@link Setting} that backs it.
|
||||||
|
* If needed, subclasses can override this to handle additional UI Preference types.
|
||||||
|
*
|
||||||
|
* @param applySettingToPreference If true, then apply {@link Setting} -> Preference.
|
||||||
|
* If false, then apply {@link Setting} <- Preference.
|
||||||
|
*/
|
||||||
|
protected void syncSettingWithPreference(@NonNull Preference pref,
|
||||||
|
@NonNull Setting<?> setting,
|
||||||
|
boolean applySettingToPreference) {
|
||||||
|
if (pref instanceof SwitchPreference) {
|
||||||
|
SwitchPreference switchPref = (SwitchPreference) pref;
|
||||||
|
BooleanSetting boolSetting = (BooleanSetting) setting;
|
||||||
|
if (applySettingToPreference) {
|
||||||
|
switchPref.setChecked(boolSetting.get());
|
||||||
|
} else {
|
||||||
|
BooleanSetting.privateSetValue(boolSetting, switchPref.isChecked());
|
||||||
|
}
|
||||||
|
} else if (pref instanceof EditTextPreference) {
|
||||||
|
EditTextPreference editPreference = (EditTextPreference) pref;
|
||||||
|
if (applySettingToPreference) {
|
||||||
|
editPreference.setText(setting.get().toString());
|
||||||
|
} else {
|
||||||
|
Setting.privateSetValueFromString(setting, editPreference.getText());
|
||||||
|
}
|
||||||
|
} else if (pref instanceof ListPreference) {
|
||||||
|
ListPreference listPref = (ListPreference) pref;
|
||||||
|
if (applySettingToPreference) {
|
||||||
|
listPref.setValue(setting.get().toString());
|
||||||
|
} else {
|
||||||
|
Setting.privateSetValueFromString(setting, listPref.getValue());
|
||||||
|
}
|
||||||
|
updateListPreferenceSummary(listPref, setting);
|
||||||
|
} else {
|
||||||
|
Logger.printException(() -> "Setting cannot be handled: " + pref.getClass() + ": " + pref);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates a UI Preference with the {@link Setting} that backs it.
|
||||||
|
*
|
||||||
|
* @param syncSetting If the UI should be synced {@link Setting} <-> Preference
|
||||||
|
* @param applySettingToPreference If true, then apply {@link Setting} -> Preference.
|
||||||
|
* If false, then apply {@link Setting} <- Preference.
|
||||||
|
*/
|
||||||
|
private void updatePreference(@NonNull Preference pref, @NonNull Setting<?> setting,
|
||||||
|
boolean syncSetting, boolean applySettingToPreference) {
|
||||||
|
if (!syncSetting && applySettingToPreference) {
|
||||||
|
throw new IllegalArgumentException();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (syncSetting) {
|
||||||
|
syncSettingWithPreference(pref, setting, applySettingToPreference);
|
||||||
|
}
|
||||||
|
|
||||||
|
updatePreferenceAvailability(pref, setting);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void updatePreferenceAvailability(@NonNull Preference pref, @NonNull Setting<?> setting) {
|
||||||
|
pref.setEnabled(setting.isAvailable());
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void updateListPreferenceSummary(ListPreference listPreference, Setting<?> setting) {
|
||||||
|
String objectStringValue = setting.get().toString();
|
||||||
|
final int entryIndex = listPreference.findIndexOfValue(objectStringValue);
|
||||||
|
if (entryIndex >= 0) {
|
||||||
|
listPreference.setSummary(listPreference.getEntries()[entryIndex]);
|
||||||
|
} else {
|
||||||
|
// Value is not an available option.
|
||||||
|
// User manually edited import data, or options changed and current selection is no longer available.
|
||||||
|
// Still show the value in the summary, so it's clear that something is selected.
|
||||||
|
listPreference.setSummary(objectStringValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void showRestartDialog(@NonNull final Context context) {
|
||||||
|
Utils.verifyOnMainThread();
|
||||||
|
if (restartDialogTitle == null) {
|
||||||
|
restartDialogTitle = str("revanced_settings_restart_title");
|
||||||
|
}
|
||||||
|
if (restartDialogButtonText == null) {
|
||||||
|
restartDialogButtonText = str("revanced_settings_restart");
|
||||||
|
}
|
||||||
|
new AlertDialog.Builder(context)
|
||||||
|
.setMessage(restartDialogTitle)
|
||||||
|
.setPositiveButton(restartDialogButtonText, (dialog, id)
|
||||||
|
-> Utils.restartApp(context))
|
||||||
|
.setNegativeButton(android.R.string.cancel, null)
|
||||||
|
.setCancelable(false)
|
||||||
|
.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("ResourceType")
|
||||||
|
@Override
|
||||||
|
public void onCreate(Bundle savedInstanceState) {
|
||||||
|
super.onCreate(savedInstanceState);
|
||||||
|
try {
|
||||||
|
PreferenceManager preferenceManager = getPreferenceManager();
|
||||||
|
preferenceManager.setSharedPreferencesName(Setting.preferences.name);
|
||||||
|
|
||||||
|
// Must initialize before adding change listener,
|
||||||
|
// otherwise the syncing of Setting -> UI
|
||||||
|
// causes a callback to the listener even though nothing changed.
|
||||||
|
initialize();
|
||||||
|
updateUIToSettingValues();
|
||||||
|
|
||||||
|
preferenceManager.getSharedPreferences().registerOnSharedPreferenceChangeListener(listener);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "onCreate() failure", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onDestroy() {
|
||||||
|
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listener);
|
||||||
|
super.onDestroy();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,99 @@
|
|||||||
|
package app.revanced.extension.shared.settings.preference;
|
||||||
|
|
||||||
|
import android.app.AlertDialog;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.os.Build;
|
||||||
|
import android.preference.EditTextPreference;
|
||||||
|
import android.preference.Preference;
|
||||||
|
import android.text.InputType;
|
||||||
|
import android.util.AttributeSet;
|
||||||
|
import android.util.TypedValue;
|
||||||
|
import android.widget.EditText;
|
||||||
|
import app.revanced.extension.shared.settings.Setting;
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
|
||||||
|
@SuppressWarnings({"unused", "deprecation"})
|
||||||
|
public class ImportExportPreference extends EditTextPreference implements Preference.OnPreferenceClickListener {
|
||||||
|
|
||||||
|
private String existingSettings;
|
||||||
|
|
||||||
|
private void init() {
|
||||||
|
setSelectable(true);
|
||||||
|
|
||||||
|
EditText editText = getEditText();
|
||||||
|
editText.setTextIsSelectable(true);
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
editText.setAutofillHints((String) null);
|
||||||
|
}
|
||||||
|
editText.setInputType(editText.getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
|
||||||
|
editText.setTextSize(TypedValue.COMPLEX_UNIT_PT, 7); // Use a smaller font to reduce text wrap.
|
||||||
|
|
||||||
|
setOnPreferenceClickListener(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ImportExportPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||||
|
super(context, attrs, defStyleAttr, defStyleRes);
|
||||||
|
init();
|
||||||
|
}
|
||||||
|
public ImportExportPreference(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||||
|
super(context, attrs, defStyleAttr);
|
||||||
|
init();
|
||||||
|
}
|
||||||
|
public ImportExportPreference(Context context, AttributeSet attrs) {
|
||||||
|
super(context, attrs);
|
||||||
|
init();
|
||||||
|
}
|
||||||
|
public ImportExportPreference(Context context) {
|
||||||
|
super(context);
|
||||||
|
init();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onPreferenceClick(Preference preference) {
|
||||||
|
try {
|
||||||
|
// Must set text before preparing dialog, otherwise text is non selectable if this preference is later reopened.
|
||||||
|
existingSettings = Setting.exportToJson(getContext());
|
||||||
|
getEditText().setText(existingSettings);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "showDialog failure", ex);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
|
||||||
|
try {
|
||||||
|
Utils.setEditTextDialogTheme(builder);
|
||||||
|
|
||||||
|
// Show the user the settings in JSON format.
|
||||||
|
builder.setNeutralButton(str("revanced_settings_import_copy"), (dialog, which) -> {
|
||||||
|
Utils.setClipboard(getEditText().getText().toString());
|
||||||
|
}).setPositiveButton(str("revanced_settings_import"), (dialog, which) -> {
|
||||||
|
importSettings(getEditText().getText().toString());
|
||||||
|
});
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "onPrepareDialogBuilder failure", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void importSettings(String replacementSettings) {
|
||||||
|
try {
|
||||||
|
if (replacementSettings.equals(existingSettings)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
AbstractPreferenceFragment.settingImportInProgress = true;
|
||||||
|
final boolean rebootNeeded = Setting.importFromJSON(replacementSettings);
|
||||||
|
if (rebootNeeded) {
|
||||||
|
AbstractPreferenceFragment.showRestartDialog(getContext());
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "importSettings failure", ex);
|
||||||
|
} finally {
|
||||||
|
AbstractPreferenceFragment.settingImportInProgress = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,325 @@
|
|||||||
|
package app.revanced.extension.shared.settings.preference;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.sf;
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
import static app.revanced.extension.youtube.requests.Route.Method.GET;
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint;
|
||||||
|
import android.app.Dialog;
|
||||||
|
import android.app.ProgressDialog;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.content.res.Configuration;
|
||||||
|
import android.graphics.Color;
|
||||||
|
import android.net.Uri;
|
||||||
|
import android.os.Bundle;
|
||||||
|
import android.preference.Preference;
|
||||||
|
import android.util.AttributeSet;
|
||||||
|
import android.view.Window;
|
||||||
|
import android.webkit.WebView;
|
||||||
|
import android.webkit.WebViewClient;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import org.json.JSONArray;
|
||||||
|
import org.json.JSONException;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.SocketTimeoutException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
import app.revanced.extension.youtube.requests.Requester;
|
||||||
|
import app.revanced.extension.youtube.requests.Route;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens a dialog showing the links from {@link SocialLinksRoutes}.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings({"unused", "deprecation"})
|
||||||
|
public class ReVancedAboutPreference extends Preference {
|
||||||
|
|
||||||
|
private static String useNonBreakingHyphens(String text) {
|
||||||
|
// Replace any dashes with non breaking dashes, so the English text 'pre-release'
|
||||||
|
// and the dev release number does not break and cover two lines.
|
||||||
|
return text.replace("-", "‑"); // #8209 = non breaking hyphen.
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String getColorHexString(int color) {
|
||||||
|
return String.format("#%06X", (0x00FFFFFF & color));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean isDarkModeEnabled() {
|
||||||
|
Configuration config = getContext().getResources().getConfiguration();
|
||||||
|
final int currentNightMode = config.uiMode & Configuration.UI_MODE_NIGHT_MASK;
|
||||||
|
return currentNightMode == Configuration.UI_MODE_NIGHT_YES;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subclasses can override this and provide a themed color.
|
||||||
|
*/
|
||||||
|
protected int getLightColor() {
|
||||||
|
return Color.WHITE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subclasses can override this and provide a themed color.
|
||||||
|
*/
|
||||||
|
protected int getDarkColor() {
|
||||||
|
return Color.BLACK;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String createDialogHtml(WebLink[] socialLinks) {
|
||||||
|
final boolean isNetworkConnected = Utils.isNetworkConnected();
|
||||||
|
|
||||||
|
StringBuilder builder = new StringBuilder();
|
||||||
|
builder.append("<html>");
|
||||||
|
builder.append("<body style=\"text-align: center; padding: 10px;\">");
|
||||||
|
|
||||||
|
final boolean isDarkMode = isDarkModeEnabled();
|
||||||
|
String backgroundColorHex = getColorHexString(isDarkMode ? getDarkColor() : getLightColor());
|
||||||
|
String foregroundColorHex = getColorHexString(isDarkMode ? getLightColor() : getDarkColor());
|
||||||
|
// Apply light/dark mode colors.
|
||||||
|
builder.append(String.format(
|
||||||
|
"<style> body { background-color: %s; color: %s; } a { color: %s; } </style>",
|
||||||
|
backgroundColorHex, foregroundColorHex, foregroundColorHex));
|
||||||
|
|
||||||
|
if (isNetworkConnected) {
|
||||||
|
builder.append("<img style=\"width: 100px; height: 100px;\" "
|
||||||
|
// Hide the image if it does not load.
|
||||||
|
+ "onerror=\"this.style.display='none';\" "
|
||||||
|
+ "src=\"https://revanced.app/favicon.ico\" />");
|
||||||
|
}
|
||||||
|
|
||||||
|
String patchesVersion = Utils.getPatchesReleaseVersion();
|
||||||
|
|
||||||
|
// Add the title.
|
||||||
|
builder.append("<h1>")
|
||||||
|
.append("ReVanced")
|
||||||
|
.append("</h1>");
|
||||||
|
|
||||||
|
builder.append("<p>")
|
||||||
|
// Replace hyphens with non breaking dashes so the version number does not break lines.
|
||||||
|
.append(useNonBreakingHyphens(str("revanced_settings_about_links_body", patchesVersion)))
|
||||||
|
.append("</p>");
|
||||||
|
|
||||||
|
// Add a disclaimer if using a dev release.
|
||||||
|
if (patchesVersion.contains("dev")) {
|
||||||
|
builder.append("<h3>")
|
||||||
|
// English text 'Pre-release' can break lines.
|
||||||
|
.append(useNonBreakingHyphens(str("revanced_settings_about_links_dev_header")))
|
||||||
|
.append("</h3>");
|
||||||
|
|
||||||
|
builder.append("<p>")
|
||||||
|
.append(str("revanced_settings_about_links_dev_body"))
|
||||||
|
.append("</p>");
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.append("<h2 style=\"margin-top: 30px;\">")
|
||||||
|
.append(str("revanced_settings_about_links_header"))
|
||||||
|
.append("</h2>");
|
||||||
|
|
||||||
|
builder.append("<div>");
|
||||||
|
for (WebLink social : socialLinks) {
|
||||||
|
builder.append("<div style=\"margin-bottom: 20px;\">");
|
||||||
|
builder.append(String.format("<a href=\"%s\">%s</a>", social.url, social.name));
|
||||||
|
builder.append("</div>");
|
||||||
|
}
|
||||||
|
builder.append("</div>");
|
||||||
|
|
||||||
|
builder.append("</body></html>");
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
setOnPreferenceClickListener(pref -> {
|
||||||
|
// Show a progress spinner if the social links are not fetched yet.
|
||||||
|
if (!SocialLinksRoutes.hasFetchedLinks() && Utils.isNetworkConnected()) {
|
||||||
|
ProgressDialog progress = new ProgressDialog(getContext());
|
||||||
|
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
|
||||||
|
progress.show();
|
||||||
|
Utils.runOnBackgroundThread(() -> fetchLinksAndShowDialog(progress));
|
||||||
|
} else {
|
||||||
|
// No network call required and can run now.
|
||||||
|
fetchLinksAndShowDialog(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fetchLinksAndShowDialog(@Nullable ProgressDialog progress) {
|
||||||
|
WebLink[] socialLinks = SocialLinksRoutes.fetchSocialLinks();
|
||||||
|
String htmlDialog = createDialogHtml(socialLinks);
|
||||||
|
|
||||||
|
Utils.runOnMainThreadNowOrLater(() -> {
|
||||||
|
if (progress != null) {
|
||||||
|
progress.dismiss();
|
||||||
|
}
|
||||||
|
new WebViewDialog(getContext(), htmlDialog).show();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public ReVancedAboutPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||||
|
super(context, attrs, defStyleAttr, defStyleRes);
|
||||||
|
}
|
||||||
|
public ReVancedAboutPreference(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||||
|
super(context, attrs, defStyleAttr);
|
||||||
|
}
|
||||||
|
public ReVancedAboutPreference(Context context, AttributeSet attrs) {
|
||||||
|
super(context, attrs);
|
||||||
|
}
|
||||||
|
public ReVancedAboutPreference(Context context) {
|
||||||
|
super(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays html content as a dialog. Any links a user taps on are opened in an external browser.
|
||||||
|
*/
|
||||||
|
class WebViewDialog extends Dialog {
|
||||||
|
|
||||||
|
private final String htmlContent;
|
||||||
|
|
||||||
|
public WebViewDialog(@NonNull Context context, @NonNull String htmlContent) {
|
||||||
|
super(context);
|
||||||
|
this.htmlContent = htmlContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
// JS required to hide any broken images. No remote javascript is ever loaded.
|
||||||
|
@SuppressLint("SetJavaScriptEnabled")
|
||||||
|
@Override
|
||||||
|
protected void onCreate(Bundle savedInstanceState) {
|
||||||
|
super.onCreate(savedInstanceState);
|
||||||
|
requestWindowFeature(Window.FEATURE_NO_TITLE);
|
||||||
|
|
||||||
|
WebView webView = new WebView(getContext());
|
||||||
|
webView.getSettings().setJavaScriptEnabled(true);
|
||||||
|
webView.setWebViewClient(new OpenLinksExternallyWebClient());
|
||||||
|
webView.loadDataWithBaseURL(null, htmlContent, "text/html", "utf-8", null);
|
||||||
|
|
||||||
|
setContentView(webView);
|
||||||
|
}
|
||||||
|
|
||||||
|
private class OpenLinksExternallyWebClient extends WebViewClient {
|
||||||
|
@Override
|
||||||
|
public boolean shouldOverrideUrlLoading(WebView view, String url) {
|
||||||
|
try {
|
||||||
|
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
|
||||||
|
getContext().startActivity(intent);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "Open link failure", ex);
|
||||||
|
}
|
||||||
|
// Dismiss the about dialog using a delay,
|
||||||
|
// otherwise without a delay the UI looks hectic with the dialog dismissing
|
||||||
|
// to show the settings while simultaneously a web browser is opening.
|
||||||
|
Utils.runOnMainThreadDelayed(WebViewDialog.this::dismiss, 500);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class WebLink {
|
||||||
|
final boolean preferred;
|
||||||
|
final String name;
|
||||||
|
final String url;
|
||||||
|
|
||||||
|
WebLink(JSONObject json) throws JSONException {
|
||||||
|
this(json.getBoolean("preferred"),
|
||||||
|
json.getString("name"),
|
||||||
|
json.getString("url")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
WebLink(boolean preferred, String name, String url) {
|
||||||
|
this.preferred = preferred;
|
||||||
|
this.name = name;
|
||||||
|
this.url = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "ReVancedSocialLink{" +
|
||||||
|
"preferred=" + preferred +
|
||||||
|
", name='" + name + '\'' +
|
||||||
|
", url='" + url + '\'' +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SocialLinksRoutes {
|
||||||
|
/**
|
||||||
|
* Simple link to the website donate page,
|
||||||
|
* rather than fetching and parsing the donation links using the API.
|
||||||
|
*/
|
||||||
|
public static final WebLink DONATE_LINK = new WebLink(true,
|
||||||
|
sf("revanced_settings_about_links_donate").toString(),
|
||||||
|
"https://revanced.app/donate");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Links to use if fetch links api call fails.
|
||||||
|
*/
|
||||||
|
private static final WebLink[] NO_CONNECTION_STATIC_LINKS = {
|
||||||
|
new WebLink(true, "ReVanced.app", "https://revanced.app"),
|
||||||
|
DONATE_LINK,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static final String SOCIAL_LINKS_PROVIDER = "https://api.revanced.app/v2";
|
||||||
|
private static final Route.CompiledRoute GET_SOCIAL = new Route(GET, "/socials").compile();
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
private static volatile WebLink[] fetchedLinks;
|
||||||
|
|
||||||
|
static boolean hasFetchedLinks() {
|
||||||
|
return fetchedLinks != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static WebLink[] fetchSocialLinks() {
|
||||||
|
try {
|
||||||
|
if (hasFetchedLinks()) return fetchedLinks;
|
||||||
|
|
||||||
|
// Check if there is no internet connection.
|
||||||
|
if (!Utils.isNetworkConnected()) return NO_CONNECTION_STATIC_LINKS;
|
||||||
|
|
||||||
|
HttpURLConnection connection = Requester.getConnectionFromCompiledRoute(SOCIAL_LINKS_PROVIDER, GET_SOCIAL);
|
||||||
|
connection.setConnectTimeout(5000);
|
||||||
|
connection.setReadTimeout(5000);
|
||||||
|
Logger.printDebug(() -> "Fetching social links from: " + connection.getURL());
|
||||||
|
|
||||||
|
// Do not show an exception toast if the server is down
|
||||||
|
final int responseCode = connection.getResponseCode();
|
||||||
|
if (responseCode != 200) {
|
||||||
|
Logger.printDebug(() -> "Failed to get social links. Response code: " + responseCode);
|
||||||
|
return NO_CONNECTION_STATIC_LINKS;
|
||||||
|
}
|
||||||
|
|
||||||
|
JSONObject json = Requester.parseJSONObjectAndDisconnect(connection);
|
||||||
|
JSONArray socials = json.getJSONArray("socials");
|
||||||
|
|
||||||
|
List<WebLink> links = new ArrayList<>();
|
||||||
|
|
||||||
|
links.add(DONATE_LINK); // Show donate link first.
|
||||||
|
for (int i = 0, length = socials.length(); i < length; i++) {
|
||||||
|
WebLink link = new WebLink(socials.getJSONObject(i));
|
||||||
|
links.add(link);
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.printDebug(() -> "links: " + links);
|
||||||
|
|
||||||
|
return fetchedLinks = links.toArray(new WebLink[0]);
|
||||||
|
|
||||||
|
} catch (SocketTimeoutException ex) {
|
||||||
|
Logger.printInfo(() -> "Could not fetch social links", ex); // No toast.
|
||||||
|
} catch (JSONException ex) {
|
||||||
|
Logger.printException(() -> "Could not parse about information", ex);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "Failed to get about information", ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NO_CONNECTION_STATIC_LINKS;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,67 @@
|
|||||||
|
package app.revanced.extension.shared.settings.preference;
|
||||||
|
|
||||||
|
import android.app.AlertDialog;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.os.Bundle;
|
||||||
|
import android.preference.EditTextPreference;
|
||||||
|
import android.util.AttributeSet;
|
||||||
|
import android.widget.Button;
|
||||||
|
import android.widget.EditText;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
import app.revanced.extension.shared.settings.Setting;
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
|
||||||
|
@SuppressWarnings({"unused", "deprecation"})
|
||||||
|
public class ResettableEditTextPreference extends EditTextPreference {
|
||||||
|
|
||||||
|
public ResettableEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||||
|
super(context, attrs, defStyleAttr, defStyleRes);
|
||||||
|
}
|
||||||
|
public ResettableEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||||
|
super(context, attrs, defStyleAttr);
|
||||||
|
}
|
||||||
|
public ResettableEditTextPreference(Context context, AttributeSet attrs) {
|
||||||
|
super(context, attrs);
|
||||||
|
}
|
||||||
|
public ResettableEditTextPreference(Context context) {
|
||||||
|
super(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
|
||||||
|
super.onPrepareDialogBuilder(builder);
|
||||||
|
Utils.setEditTextDialogTheme(builder);
|
||||||
|
|
||||||
|
Setting<?> setting = Setting.getSettingFromPath(getKey());
|
||||||
|
if (setting != null) {
|
||||||
|
builder.setNeutralButton(str("revanced_settings_reset"), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void showDialog(Bundle state) {
|
||||||
|
super.showDialog(state);
|
||||||
|
|
||||||
|
// Override the button click listener to prevent dismissing the dialog.
|
||||||
|
Button button = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_NEUTRAL);
|
||||||
|
if (button == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
button.setOnClickListener(v -> {
|
||||||
|
try {
|
||||||
|
Setting<?> setting = Objects.requireNonNull(Setting.getSettingFromPath(getKey()));
|
||||||
|
String defaultStringValue = setting.defaultValue.toString();
|
||||||
|
EditText editText = getEditText();
|
||||||
|
editText.setText(defaultStringValue);
|
||||||
|
editText.setSelection(defaultStringValue.length()); // move cursor to end of text
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "reset failure", ex);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,190 @@
|
|||||||
|
package app.revanced.extension.shared.settings.preference;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.SharedPreferences;
|
||||||
|
import android.preference.PreferenceFragment;
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared categories, and helper methods.
|
||||||
|
*
|
||||||
|
* The various save methods store numbers as Strings,
|
||||||
|
* which is required if using {@link PreferenceFragment}.
|
||||||
|
*
|
||||||
|
* If saved numbers will not be used with a preference fragment,
|
||||||
|
* then store the primitive numbers using the {@link #preferences} itself.
|
||||||
|
*/
|
||||||
|
public class SharedPrefCategory {
|
||||||
|
@NonNull
|
||||||
|
public final String name;
|
||||||
|
@NonNull
|
||||||
|
public final SharedPreferences preferences;
|
||||||
|
|
||||||
|
public SharedPrefCategory(@NonNull String name) {
|
||||||
|
this.name = Objects.requireNonNull(name);
|
||||||
|
preferences = Objects.requireNonNull(Utils.getContext()).getSharedPreferences(name, Context.MODE_PRIVATE);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void removeConflictingPreferenceKeyValue(@NonNull String key) {
|
||||||
|
Logger.printException(() -> "Found conflicting preference: " + key);
|
||||||
|
removeKey(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveObjectAsString(@NonNull String key, @Nullable Object value) {
|
||||||
|
preferences.edit().putString(key, (value == null ? null : value.toString())).apply();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes any preference data type that has the specified key.
|
||||||
|
*/
|
||||||
|
public void removeKey(@NonNull String key) {
|
||||||
|
preferences.edit().remove(Objects.requireNonNull(key)).apply();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void saveBoolean(@NonNull String key, boolean value) {
|
||||||
|
preferences.edit().putBoolean(key, value).apply();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param value a NULL parameter removes the value from the preferences
|
||||||
|
*/
|
||||||
|
public void saveEnumAsString(@NonNull String key, @Nullable Enum<?> value) {
|
||||||
|
saveObjectAsString(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param value a NULL parameter removes the value from the preferences
|
||||||
|
*/
|
||||||
|
public void saveIntegerString(@NonNull String key, @Nullable Integer value) {
|
||||||
|
saveObjectAsString(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param value a NULL parameter removes the value from the preferences
|
||||||
|
*/
|
||||||
|
public void saveLongString(@NonNull String key, @Nullable Long value) {
|
||||||
|
saveObjectAsString(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param value a NULL parameter removes the value from the preferences
|
||||||
|
*/
|
||||||
|
public void saveFloatString(@NonNull String key, @Nullable Float value) {
|
||||||
|
saveObjectAsString(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param value a NULL parameter removes the value from the preferences
|
||||||
|
*/
|
||||||
|
public void saveString(@NonNull String key, @Nullable String value) {
|
||||||
|
saveObjectAsString(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
public String getString(@NonNull String key, @NonNull String _default) {
|
||||||
|
Objects.requireNonNull(_default);
|
||||||
|
try {
|
||||||
|
return preferences.getString(key, _default);
|
||||||
|
} catch (ClassCastException ex) {
|
||||||
|
// Value stored is a completely different type (should never happen).
|
||||||
|
removeConflictingPreferenceKeyValue(key);
|
||||||
|
return _default;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
public <T extends Enum<?>> T getEnum(@NonNull String key, @NonNull T _default) {
|
||||||
|
Objects.requireNonNull(_default);
|
||||||
|
try {
|
||||||
|
String enumName = preferences.getString(key, null);
|
||||||
|
if (enumName != null) {
|
||||||
|
try {
|
||||||
|
// noinspection unchecked
|
||||||
|
return (T) Enum.valueOf(_default.getClass(), enumName);
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
// Info level to allow removing enum values in the future without showing any user errors.
|
||||||
|
Logger.printInfo(() -> "Using default, and ignoring unknown enum value: " + enumName);
|
||||||
|
removeKey(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (ClassCastException ex) {
|
||||||
|
// Value stored is a completely different type (should never happen).
|
||||||
|
removeConflictingPreferenceKeyValue(key);
|
||||||
|
}
|
||||||
|
return _default;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean getBoolean(@NonNull String key, boolean _default) {
|
||||||
|
try {
|
||||||
|
return preferences.getBoolean(key, _default);
|
||||||
|
} catch (ClassCastException ex) {
|
||||||
|
// Value stored is a completely different type (should never happen).
|
||||||
|
removeConflictingPreferenceKeyValue(key);
|
||||||
|
return _default;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
public Integer getIntegerString(@NonNull String key, @NonNull Integer _default) {
|
||||||
|
try {
|
||||||
|
String value = preferences.getString(key, null);
|
||||||
|
if (value != null) {
|
||||||
|
return Integer.valueOf(value);
|
||||||
|
}
|
||||||
|
} catch (ClassCastException | NumberFormatException ex) {
|
||||||
|
try {
|
||||||
|
// Old data previously stored as primitive.
|
||||||
|
return preferences.getInt(key, _default);
|
||||||
|
} catch (ClassCastException ex2) {
|
||||||
|
// Value stored is a completely different type (should never happen).
|
||||||
|
removeConflictingPreferenceKeyValue(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return _default;
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
public Long getLongString(@NonNull String key, @NonNull Long _default) {
|
||||||
|
try {
|
||||||
|
String value = preferences.getString(key, null);
|
||||||
|
if (value != null) {
|
||||||
|
return Long.valueOf(value);
|
||||||
|
}
|
||||||
|
} catch (ClassCastException | NumberFormatException ex) {
|
||||||
|
try {
|
||||||
|
return preferences.getLong(key, _default);
|
||||||
|
} catch (ClassCastException ex2) {
|
||||||
|
removeConflictingPreferenceKeyValue(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return _default;
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
public Float getFloatString(@NonNull String key, @NonNull Float _default) {
|
||||||
|
try {
|
||||||
|
String value = preferences.getString(key, null);
|
||||||
|
if (value != null) {
|
||||||
|
return Float.valueOf(value);
|
||||||
|
}
|
||||||
|
} catch (ClassCastException | NumberFormatException ex) {
|
||||||
|
try {
|
||||||
|
return preferences.getFloat(key, _default);
|
||||||
|
} catch (ClassCastException ex2) {
|
||||||
|
removeConflictingPreferenceKeyValue(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return _default;
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,77 @@
|
|||||||
|
package app.revanced.extension.syncforreddit;
|
||||||
|
|
||||||
|
import android.util.Pair;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
import org.w3c.dom.Element;
|
||||||
|
import org.xml.sax.SAXException;
|
||||||
|
|
||||||
|
import javax.xml.parsers.DocumentBuilderFactory;
|
||||||
|
import javax.xml.parsers.ParserConfigurationException;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @noinspection unused
|
||||||
|
*/
|
||||||
|
public class FixRedditVideoDownloadPatch {
|
||||||
|
private static @Nullable Pair<Integer, String> getBestMpEntry(Element element) {
|
||||||
|
var representations = element.getElementsByTagName("Representation");
|
||||||
|
var entries = new ArrayList<Pair<Integer, String>>();
|
||||||
|
|
||||||
|
for (int i = 0; i < representations.getLength(); i++) {
|
||||||
|
Element representation = (Element) representations.item(i);
|
||||||
|
var bandwidthStr = representation.getAttribute("bandwidth");
|
||||||
|
try {
|
||||||
|
var bandwidth = Integer.parseInt(bandwidthStr);
|
||||||
|
var baseUrl = representation.getElementsByTagName("BaseURL").item(0);
|
||||||
|
if (baseUrl != null) {
|
||||||
|
entries.add(new Pair<>(bandwidth, baseUrl.getTextContent()));
|
||||||
|
}
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entries.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Collections.sort(entries, (e1, e2) -> e2.first - e1.first);
|
||||||
|
return entries.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String[] parse(byte[] data) throws ParserConfigurationException, IOException, SAXException {
|
||||||
|
var adaptionSets = DocumentBuilderFactory
|
||||||
|
.newInstance()
|
||||||
|
.newDocumentBuilder()
|
||||||
|
.parse(new ByteArrayInputStream(data))
|
||||||
|
.getElementsByTagName("AdaptationSet");
|
||||||
|
|
||||||
|
String videoUrl = null;
|
||||||
|
String audioUrl = null;
|
||||||
|
|
||||||
|
for (int i = 0; i < adaptionSets.getLength(); i++) {
|
||||||
|
Element element = (Element) adaptionSets.item(i);
|
||||||
|
var contentType = element.getAttribute("contentType");
|
||||||
|
var bestEntry = getBestMpEntry(element);
|
||||||
|
if (bestEntry == null) continue;
|
||||||
|
|
||||||
|
if (contentType.equalsIgnoreCase("video")) {
|
||||||
|
videoUrl = bestEntry.second;
|
||||||
|
} else if (contentType.equalsIgnoreCase("audio")) {
|
||||||
|
audioUrl = bestEntry.second;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new String[]{videoUrl, audioUrl};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String[] getLinks(byte[] data) {
|
||||||
|
try {
|
||||||
|
return parse(data);
|
||||||
|
} catch (ParserConfigurationException | IOException | SAXException e) {
|
||||||
|
return new String[]{null, null};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package app.revanced.extension.syncforreddit;
|
||||||
|
|
||||||
|
import com.laurencedawson.reddit_sync.ui.activities.WebViewActivity;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.fixes.slink.BaseFixSLinksPatch;
|
||||||
|
|
||||||
|
/** @noinspection unused*/
|
||||||
|
public class FixSLinksPatch extends BaseFixSLinksPatch {
|
||||||
|
static {
|
||||||
|
INSTANCE = new FixSLinksPatch();
|
||||||
|
}
|
||||||
|
|
||||||
|
private FixSLinksPatch() {
|
||||||
|
webViewActivityClass = WebViewActivity.class;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean patchResolveSLink(String link) {
|
||||||
|
return INSTANCE.resolveSLink(link);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void patchSetAccessToken(String accessToken) {
|
||||||
|
INSTANCE.setAccessToken(accessToken);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package app.revanced.extension.tiktok;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.settings.StringSetting;
|
||||||
|
|
||||||
|
public class Utils {
|
||||||
|
|
||||||
|
// Edit: This could be handled using a custom Setting<Long[]> class
|
||||||
|
// that saves its value to preferences and JSON using the formatted String created here.
|
||||||
|
public static long[] parseMinMax(StringSetting setting) {
|
||||||
|
final String[] minMax = setting.get().split("-");
|
||||||
|
if (minMax.length == 2) {
|
||||||
|
try {
|
||||||
|
final long min = Long.parseLong(minMax[0]);
|
||||||
|
final long max = Long.parseLong(minMax[1]);
|
||||||
|
|
||||||
|
if (min <= max && min >= 0) return new long[]{min, max};
|
||||||
|
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setting.save("0-" + Long.MAX_VALUE);
|
||||||
|
return new long[]{0L, Long.MAX_VALUE};
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package app.revanced.extension.tiktok.cleardisplay;
|
||||||
|
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class RememberClearDisplayPatch {
|
||||||
|
public static boolean getClearDisplayState() {
|
||||||
|
return Settings.CLEAR_DISPLAY.get();
|
||||||
|
}
|
||||||
|
public static void rememberClearDisplayState(boolean newState) {
|
||||||
|
Settings.CLEAR_DISPLAY.save(newState);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package app.revanced.extension.tiktok.download;
|
||||||
|
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class DownloadsPatch {
|
||||||
|
public static String getDownloadPath() {
|
||||||
|
return Settings.DOWNLOAD_PATH.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean shouldRemoveWatermark() {
|
||||||
|
return Settings.DOWNLOAD_WATERMARK.get();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package app.revanced.extension.tiktok.feedfilter;
|
||||||
|
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
import com.ss.android.ugc.aweme.feed.model.Aweme;
|
||||||
|
|
||||||
|
public class AdsFilter implements IFilter {
|
||||||
|
@Override
|
||||||
|
public boolean getEnabled() {
|
||||||
|
return Settings.REMOVE_ADS.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getFiltered(Aweme item) {
|
||||||
|
return item.isAd() || item.isWithPromotionalMusic();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package app.revanced.extension.tiktok.feedfilter;
|
||||||
|
|
||||||
|
import com.ss.android.ugc.aweme.feed.model.Aweme;
|
||||||
|
import com.ss.android.ugc.aweme.feed.model.FeedItemList;
|
||||||
|
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public final class FeedItemsFilter {
|
||||||
|
private static final List<IFilter> FILTERS = List.of(
|
||||||
|
new AdsFilter(),
|
||||||
|
new LiveFilter(),
|
||||||
|
new StoryFilter(),
|
||||||
|
new ImageVideoFilter(),
|
||||||
|
new ViewCountFilter(),
|
||||||
|
new LikeCountFilter()
|
||||||
|
);
|
||||||
|
|
||||||
|
public static void filter(FeedItemList feedItemList) {
|
||||||
|
Iterator<Aweme> feedItemListIterator = feedItemList.items.iterator();
|
||||||
|
while (feedItemListIterator.hasNext()) {
|
||||||
|
Aweme item = feedItemListIterator.next();
|
||||||
|
if (item == null) continue;
|
||||||
|
|
||||||
|
for (IFilter filter : FILTERS) {
|
||||||
|
boolean enabled = filter.getEnabled();
|
||||||
|
if (enabled && filter.getFiltered(item)) {
|
||||||
|
feedItemListIterator.remove();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
package app.revanced.extension.tiktok.feedfilter;
|
||||||
|
|
||||||
|
import com.ss.android.ugc.aweme.feed.model.Aweme;
|
||||||
|
|
||||||
|
public interface IFilter {
|
||||||
|
boolean getEnabled();
|
||||||
|
|
||||||
|
boolean getFiltered(Aweme item);
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package app.revanced.extension.tiktok.feedfilter;
|
||||||
|
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
import com.ss.android.ugc.aweme.feed.model.Aweme;
|
||||||
|
|
||||||
|
public class ImageVideoFilter implements IFilter {
|
||||||
|
@Override
|
||||||
|
public boolean getEnabled() {
|
||||||
|
return Settings.HIDE_IMAGE.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getFiltered(Aweme item) {
|
||||||
|
return item.isImage() || item.isPhotoMode();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package app.revanced.extension.tiktok.feedfilter;
|
||||||
|
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
import com.ss.android.ugc.aweme.feed.model.Aweme;
|
||||||
|
import com.ss.android.ugc.aweme.feed.model.AwemeStatistics;
|
||||||
|
|
||||||
|
import static app.revanced.extension.tiktok.Utils.parseMinMax;
|
||||||
|
|
||||||
|
public final class LikeCountFilter implements IFilter {
|
||||||
|
final long minLike;
|
||||||
|
final long maxLike;
|
||||||
|
|
||||||
|
LikeCountFilter() {
|
||||||
|
long[] minMax = parseMinMax(Settings.MIN_MAX_LIKES);
|
||||||
|
minLike = minMax[0];
|
||||||
|
maxLike = minMax[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getEnabled() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getFiltered(Aweme item) {
|
||||||
|
AwemeStatistics statistics = item.getStatistics();
|
||||||
|
if (statistics == null) return false;
|
||||||
|
|
||||||
|
long likeCount = statistics.getDiggCount();
|
||||||
|
return likeCount < minLike || likeCount > maxLike;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package app.revanced.extension.tiktok.feedfilter;
|
||||||
|
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
import com.ss.android.ugc.aweme.feed.model.Aweme;
|
||||||
|
|
||||||
|
public class LiveFilter implements IFilter {
|
||||||
|
@Override
|
||||||
|
public boolean getEnabled() {
|
||||||
|
return Settings.HIDE_LIVE.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getFiltered(Aweme item) {
|
||||||
|
return item.isLive() || item.isLiveReplay();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package app.revanced.extension.tiktok.feedfilter;
|
||||||
|
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
import com.ss.android.ugc.aweme.feed.model.Aweme;
|
||||||
|
|
||||||
|
public class StoryFilter implements IFilter {
|
||||||
|
@Override
|
||||||
|
public boolean getEnabled() {
|
||||||
|
return Settings.HIDE_STORY.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getFiltered(Aweme item) {
|
||||||
|
return item.getIsTikTokStory();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package app.revanced.extension.tiktok.feedfilter;
|
||||||
|
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
import com.ss.android.ugc.aweme.feed.model.Aweme;
|
||||||
|
import com.ss.android.ugc.aweme.feed.model.AwemeStatistics;
|
||||||
|
|
||||||
|
import static app.revanced.extension.tiktok.Utils.parseMinMax;
|
||||||
|
|
||||||
|
public class ViewCountFilter implements IFilter {
|
||||||
|
final long minView;
|
||||||
|
final long maxView;
|
||||||
|
|
||||||
|
ViewCountFilter() {
|
||||||
|
long[] minMax = parseMinMax(Settings.MIN_MAX_VIEWS);
|
||||||
|
minView = minMax[0];
|
||||||
|
maxView = minMax[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getEnabled() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getFiltered(Aweme item) {
|
||||||
|
AwemeStatistics statistics = item.getStatistics();
|
||||||
|
if (statistics == null) return false;
|
||||||
|
|
||||||
|
long playCount = statistics.getPlayCount();
|
||||||
|
return playCount < minView || playCount > maxView;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,82 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.os.Bundle;
|
||||||
|
import android.preference.PreferenceFragment;
|
||||||
|
import android.view.View;
|
||||||
|
import android.widget.FrameLayout;
|
||||||
|
import android.widget.LinearLayout;
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.ReVancedPreferenceFragment;
|
||||||
|
import com.bytedance.ies.ugc.aweme.commercialize.compliance.personalization.AdPersonalizationActivity;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hooks AdPersonalizationActivity.
|
||||||
|
* <p>
|
||||||
|
* This class is responsible for injecting our own fragment by replacing the AdPersonalizationActivity.
|
||||||
|
*
|
||||||
|
* @noinspection unused
|
||||||
|
*/
|
||||||
|
public class AdPersonalizationActivityHook {
|
||||||
|
public static Object createSettingsEntry(String entryClazzName, String entryInfoClazzName) {
|
||||||
|
try {
|
||||||
|
Class<?> entryClazz = Class.forName(entryClazzName);
|
||||||
|
Class<?> entryInfoClazz = Class.forName(entryInfoClazzName);
|
||||||
|
Constructor<?> entryConstructor = entryClazz.getConstructor(entryInfoClazz);
|
||||||
|
Constructor<?> entryInfoConstructor = entryInfoClazz.getDeclaredConstructors()[0];
|
||||||
|
Object buttonInfo = entryInfoConstructor.newInstance("ReVanced settings", null, (View.OnClickListener) view -> startSettingsActivity(), "revanced");
|
||||||
|
return entryConstructor.newInstance(buttonInfo);
|
||||||
|
} catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException |
|
||||||
|
InstantiationException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/***
|
||||||
|
* Initialize the settings menu.
|
||||||
|
* @param base The activity to initialize the settings menu on.
|
||||||
|
* @return Whether the settings menu should be initialized.
|
||||||
|
*/
|
||||||
|
public static boolean initialize(AdPersonalizationActivity base) {
|
||||||
|
Bundle extras = base.getIntent().getExtras();
|
||||||
|
if (extras != null && !extras.getBoolean("revanced", false)) return false;
|
||||||
|
|
||||||
|
SettingsStatus.load();
|
||||||
|
|
||||||
|
LinearLayout linearLayout = new LinearLayout(base);
|
||||||
|
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(-1, -1));
|
||||||
|
linearLayout.setOrientation(LinearLayout.VERTICAL);
|
||||||
|
linearLayout.setFitsSystemWindows(true);
|
||||||
|
linearLayout.setTransitionGroup(true);
|
||||||
|
|
||||||
|
FrameLayout fragment = new FrameLayout(base);
|
||||||
|
fragment.setLayoutParams(new FrameLayout.LayoutParams(-1, -1));
|
||||||
|
int fragmentId = View.generateViewId();
|
||||||
|
fragment.setId(fragmentId);
|
||||||
|
|
||||||
|
linearLayout.addView(fragment);
|
||||||
|
base.setContentView(linearLayout);
|
||||||
|
|
||||||
|
PreferenceFragment preferenceFragment = new ReVancedPreferenceFragment();
|
||||||
|
base.getFragmentManager().beginTransaction().replace(fragmentId, preferenceFragment).commit();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void startSettingsActivity() {
|
||||||
|
Context appContext = Utils.getContext();
|
||||||
|
if (appContext != null) {
|
||||||
|
Intent intent = new Intent(appContext, AdPersonalizationActivity.class);
|
||||||
|
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||||
|
intent.putExtra("revanced", true);
|
||||||
|
appContext.startActivity(intent);
|
||||||
|
} else {
|
||||||
|
Logger.printDebug(() -> "Utils.getContext() return null");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings;
|
||||||
|
|
||||||
|
import static java.lang.Boolean.FALSE;
|
||||||
|
import static java.lang.Boolean.TRUE;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.settings.BaseSettings;
|
||||||
|
import app.revanced.extension.shared.settings.BooleanSetting;
|
||||||
|
import app.revanced.extension.shared.settings.FloatSetting;
|
||||||
|
import app.revanced.extension.shared.settings.StringSetting;
|
||||||
|
|
||||||
|
public class Settings extends BaseSettings {
|
||||||
|
public static final BooleanSetting REMOVE_ADS = new BooleanSetting("remove_ads", TRUE, true);
|
||||||
|
public static final BooleanSetting HIDE_LIVE = new BooleanSetting("hide_live", FALSE, true);
|
||||||
|
public static final BooleanSetting HIDE_STORY = new BooleanSetting("hide_story", FALSE, true);
|
||||||
|
public static final BooleanSetting HIDE_IMAGE = new BooleanSetting("hide_image", FALSE, true);
|
||||||
|
public static final StringSetting MIN_MAX_VIEWS = new StringSetting("min_max_views", "0-" + Long.MAX_VALUE, true);
|
||||||
|
public static final StringSetting MIN_MAX_LIKES = new StringSetting("min_max_likes", "0-" + Long.MAX_VALUE, true);
|
||||||
|
public static final StringSetting DOWNLOAD_PATH = new StringSetting("down_path", "DCIM/TikTok");
|
||||||
|
public static final BooleanSetting DOWNLOAD_WATERMARK = new BooleanSetting("down_watermark", TRUE);
|
||||||
|
public static final BooleanSetting CLEAR_DISPLAY = new BooleanSetting("clear_display", FALSE);
|
||||||
|
public static final FloatSetting REMEMBERED_SPEED = new FloatSetting("REMEMBERED_SPEED", 1.0f);
|
||||||
|
public static final BooleanSetting SIM_SPOOF = new BooleanSetting("simspoof", TRUE, true);
|
||||||
|
public static final StringSetting SIM_SPOOF_ISO = new StringSetting("simspoof_iso", "us");
|
||||||
|
public static final StringSetting SIMSPOOF_MCCMNC = new StringSetting("simspoof_mccmnc", "310160");
|
||||||
|
public static final StringSetting SIMSPOOF_OP_NAME = new StringSetting("simspoof_op_name", "T-Mobile");
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings;
|
||||||
|
|
||||||
|
public class SettingsStatus {
|
||||||
|
public static boolean feedFilterEnabled = false;
|
||||||
|
public static boolean downloadEnabled = false;
|
||||||
|
public static boolean simSpoofEnabled = false;
|
||||||
|
|
||||||
|
public static void enableFeedFilter() {
|
||||||
|
feedFilterEnabled = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void enableDownload() {
|
||||||
|
downloadEnabled = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void enableSimSpoof() {
|
||||||
|
simSpoofEnabled = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void load() {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,124 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings.preference;
|
||||||
|
|
||||||
|
import android.app.AlertDialog;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.DialogInterface;
|
||||||
|
import android.os.Environment;
|
||||||
|
import android.preference.DialogPreference;
|
||||||
|
import android.text.Editable;
|
||||||
|
import android.text.InputType;
|
||||||
|
import android.text.TextUtils;
|
||||||
|
import android.text.TextWatcher;
|
||||||
|
import android.view.View;
|
||||||
|
import android.widget.EditText;
|
||||||
|
import android.widget.LinearLayout;
|
||||||
|
import android.widget.RadioButton;
|
||||||
|
import android.widget.RadioGroup;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.settings.StringSetting;
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public class DownloadPathPreference extends DialogPreference {
|
||||||
|
private final Context context;
|
||||||
|
private final String[] entryValues = {"DCIM", "Movies", "Pictures"};
|
||||||
|
private String mValue;
|
||||||
|
|
||||||
|
private boolean mValueSet;
|
||||||
|
private int mediaPathIndex;
|
||||||
|
private String childDownloadPath;
|
||||||
|
|
||||||
|
public DownloadPathPreference(Context context, String title, StringSetting setting) {
|
||||||
|
super(context);
|
||||||
|
this.context = context;
|
||||||
|
this.setTitle(title);
|
||||||
|
this.setSummary(Environment.getExternalStorageDirectory().getPath() + "/" + setting.get());
|
||||||
|
this.setKey(setting.key);
|
||||||
|
this.setValue(setting.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getValue() {
|
||||||
|
return this.mValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setValue(String value) {
|
||||||
|
final boolean changed = !TextUtils.equals(mValue, value);
|
||||||
|
if (changed || !mValueSet) {
|
||||||
|
mValue = value;
|
||||||
|
mValueSet = true;
|
||||||
|
persistString(value);
|
||||||
|
if (changed) {
|
||||||
|
notifyDependencyChange(shouldDisableDependents());
|
||||||
|
notifyChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected View onCreateDialogView() {
|
||||||
|
String currentMedia = getValue().split("/")[0];
|
||||||
|
childDownloadPath = getValue().substring(getValue().indexOf("/") + 1);
|
||||||
|
mediaPathIndex = findIndexOf(currentMedia);
|
||||||
|
|
||||||
|
LinearLayout dialogView = new LinearLayout(context);
|
||||||
|
RadioGroup mediaPath = new RadioGroup(context);
|
||||||
|
mediaPath.setLayoutParams(new RadioGroup.LayoutParams(-1, -2));
|
||||||
|
for (String entryValue : entryValues) {
|
||||||
|
RadioButton radioButton = new RadioButton(context);
|
||||||
|
radioButton.setText(entryValue);
|
||||||
|
radioButton.setId(View.generateViewId());
|
||||||
|
mediaPath.addView(radioButton);
|
||||||
|
}
|
||||||
|
mediaPath.setOnCheckedChangeListener((radioGroup, id) -> {
|
||||||
|
RadioButton radioButton = radioGroup.findViewById(id);
|
||||||
|
mediaPathIndex = findIndexOf(radioButton.getText().toString());
|
||||||
|
});
|
||||||
|
mediaPath.check(mediaPath.getChildAt(mediaPathIndex).getId());
|
||||||
|
EditText downloadPath = new EditText(context);
|
||||||
|
downloadPath.setInputType(InputType.TYPE_CLASS_TEXT);
|
||||||
|
downloadPath.setText(childDownloadPath);
|
||||||
|
downloadPath.addTextChangedListener(new TextWatcher() {
|
||||||
|
@Override
|
||||||
|
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterTextChanged(Editable editable) {
|
||||||
|
childDownloadPath = editable.toString();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
dialogView.setLayoutParams(new LinearLayout.LayoutParams(-1, -1));
|
||||||
|
dialogView.setOrientation(LinearLayout.VERTICAL);
|
||||||
|
dialogView.addView(mediaPath);
|
||||||
|
dialogView.addView(downloadPath);
|
||||||
|
return dialogView;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
|
||||||
|
builder.setTitle("Download Path");
|
||||||
|
builder.setPositiveButton(android.R.string.ok, (dialog, which) -> this.onClick(dialog, DialogInterface.BUTTON_POSITIVE));
|
||||||
|
builder.setNegativeButton(android.R.string.cancel, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void onDialogClosed(boolean positiveResult) {
|
||||||
|
if (positiveResult && mediaPathIndex >= 0) {
|
||||||
|
String newValue = entryValues[mediaPathIndex] + "/" + childDownloadPath;
|
||||||
|
setSummary(Environment.getExternalStorageDirectory().getPath() + "/" + newValue);
|
||||||
|
setValue(newValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int findIndexOf(String str) {
|
||||||
|
for (int i = 0; i < entryValues.length; i++) {
|
||||||
|
if (str.equals(entryValues[i])) return i;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings.preference;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.preference.EditTextPreference;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.settings.StringSetting;
|
||||||
|
|
||||||
|
public class InputTextPreference extends EditTextPreference {
|
||||||
|
|
||||||
|
public InputTextPreference(Context context, String title, String summary, StringSetting setting) {
|
||||||
|
super(context);
|
||||||
|
this.setTitle(title);
|
||||||
|
this.setSummary(summary);
|
||||||
|
this.setKey(setting.key);
|
||||||
|
this.setText(setting.get());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,130 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings.preference;
|
||||||
|
|
||||||
|
import android.app.AlertDialog;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.DialogInterface;
|
||||||
|
import android.preference.DialogPreference;
|
||||||
|
import android.text.Editable;
|
||||||
|
import android.text.InputType;
|
||||||
|
import android.text.TextUtils;
|
||||||
|
import android.text.TextWatcher;
|
||||||
|
import android.view.View;
|
||||||
|
import android.widget.EditText;
|
||||||
|
import android.widget.LinearLayout;
|
||||||
|
import android.widget.TextView;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.settings.StringSetting;
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public class RangeValuePreference extends DialogPreference {
|
||||||
|
private final Context context;
|
||||||
|
|
||||||
|
private String minValue;
|
||||||
|
|
||||||
|
private String maxValue;
|
||||||
|
|
||||||
|
private String mValue;
|
||||||
|
|
||||||
|
private boolean mValueSet;
|
||||||
|
|
||||||
|
public RangeValuePreference(Context context, String title, String summary, StringSetting setting) {
|
||||||
|
super(context);
|
||||||
|
this.context = context;
|
||||||
|
setTitle(title);
|
||||||
|
setSummary(summary);
|
||||||
|
setKey(setting.key);
|
||||||
|
setValue(setting.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setValue(String value) {
|
||||||
|
final boolean changed = !TextUtils.equals(mValue, value);
|
||||||
|
if (changed || !mValueSet) {
|
||||||
|
mValue = value;
|
||||||
|
mValueSet = true;
|
||||||
|
persistString(value);
|
||||||
|
if (changed) {
|
||||||
|
notifyDependencyChange(shouldDisableDependents());
|
||||||
|
notifyChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getValue() {
|
||||||
|
return mValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected View onCreateDialogView() {
|
||||||
|
minValue = getValue().split("-")[0];
|
||||||
|
maxValue = getValue().split("-")[1];
|
||||||
|
LinearLayout dialogView = new LinearLayout(context);
|
||||||
|
dialogView.setOrientation(LinearLayout.VERTICAL);
|
||||||
|
LinearLayout minView = new LinearLayout(context);
|
||||||
|
minView.setOrientation(LinearLayout.HORIZONTAL);
|
||||||
|
TextView min = new TextView(context);
|
||||||
|
min.setText("Min: ");
|
||||||
|
minView.addView(min);
|
||||||
|
EditText minEditText = new EditText(context);
|
||||||
|
minEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
|
||||||
|
minEditText.setText(minValue);
|
||||||
|
minView.addView(minEditText);
|
||||||
|
dialogView.addView(minView);
|
||||||
|
LinearLayout maxView = new LinearLayout(context);
|
||||||
|
maxView.setOrientation(LinearLayout.HORIZONTAL);
|
||||||
|
TextView max = new TextView(context);
|
||||||
|
max.setText("Max: ");
|
||||||
|
maxView.addView(max);
|
||||||
|
EditText maxEditText = new EditText(context);
|
||||||
|
maxEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
|
||||||
|
maxEditText.setText(maxValue);
|
||||||
|
maxView.addView(maxEditText);
|
||||||
|
dialogView.addView(maxView);
|
||||||
|
minEditText.addTextChangedListener(new TextWatcher() {
|
||||||
|
@Override
|
||||||
|
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterTextChanged(Editable editable) {
|
||||||
|
minValue = editable.toString();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
maxEditText.addTextChangedListener(new TextWatcher() {
|
||||||
|
@Override
|
||||||
|
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterTextChanged(Editable editable) {
|
||||||
|
maxValue = editable.toString();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return dialogView;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
|
||||||
|
builder.setPositiveButton(android.R.string.ok, (dialog, which) -> this.onClick(dialog, DialogInterface.BUTTON_POSITIVE));
|
||||||
|
builder.setNegativeButton(android.R.string.cancel, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void onDialogClosed(boolean positiveResult) {
|
||||||
|
if (positiveResult) {
|
||||||
|
String newValue = minValue + "-" + maxValue;
|
||||||
|
setValue(newValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,54 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings.preference;
|
||||||
|
|
||||||
|
import android.preference.Preference;
|
||||||
|
import android.preference.PreferenceScreen;
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import app.revanced.extension.shared.settings.Setting;
|
||||||
|
import app.revanced.extension.shared.settings.preference.AbstractPreferenceFragment;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.categories.DownloadsPreferenceCategory;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.categories.FeedFilterPreferenceCategory;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.categories.ExtensionPreferenceCategory;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.categories.SimSpoofPreferenceCategory;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Preference fragment for ReVanced settings
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public class ReVancedPreferenceFragment extends AbstractPreferenceFragment {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void syncSettingWithPreference(@NonNull @NotNull Preference pref,
|
||||||
|
@NonNull @NotNull Setting<?> setting,
|
||||||
|
boolean applySettingToPreference) {
|
||||||
|
if (pref instanceof RangeValuePreference) {
|
||||||
|
RangeValuePreference rangeValuePref = (RangeValuePreference) pref;
|
||||||
|
Setting.privateSetValueFromString(setting, rangeValuePref.getValue());
|
||||||
|
} else if (pref instanceof DownloadPathPreference) {
|
||||||
|
DownloadPathPreference downloadPathPref = (DownloadPathPreference) pref;
|
||||||
|
Setting.privateSetValueFromString(setting, downloadPathPref.getValue());
|
||||||
|
} else {
|
||||||
|
super.syncSettingWithPreference(pref, setting, applySettingToPreference);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void initialize() {
|
||||||
|
final var context = getContext();
|
||||||
|
|
||||||
|
// Currently no resources can be compiled for TikTok (fails with aapt error).
|
||||||
|
// So all TikTok Strings are hard coded in the extension.
|
||||||
|
restartDialogTitle = "Refresh and restart";
|
||||||
|
restartDialogButtonText = "Restart";
|
||||||
|
confirmDialogTitle = "Do you wish to proceed?";
|
||||||
|
|
||||||
|
PreferenceScreen preferenceScreen = getPreferenceManager().createPreferenceScreen(context);
|
||||||
|
setPreferenceScreen(preferenceScreen);
|
||||||
|
|
||||||
|
// Custom categories reference app specific Settings class.
|
||||||
|
new FeedFilterPreferenceCategory(context, preferenceScreen);
|
||||||
|
new DownloadsPreferenceCategory(context, preferenceScreen);
|
||||||
|
new SimSpoofPreferenceCategory(context, preferenceScreen);
|
||||||
|
new ExtensionPreferenceCategory(context, preferenceScreen);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings.preference;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.preference.SwitchPreference;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.settings.BooleanSetting;
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public class TogglePreference extends SwitchPreference {
|
||||||
|
public TogglePreference(Context context, String title, String summary, BooleanSetting setting) {
|
||||||
|
super(context);
|
||||||
|
this.setTitle(title);
|
||||||
|
this.setSummary(summary);
|
||||||
|
this.setKey(setting.key);
|
||||||
|
this.setChecked(setting.get());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings.preference.categories;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.preference.PreferenceCategory;
|
||||||
|
import android.preference.PreferenceScreen;
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public abstract class ConditionalPreferenceCategory extends PreferenceCategory {
|
||||||
|
public ConditionalPreferenceCategory(Context context, PreferenceScreen screen) {
|
||||||
|
super(context);
|
||||||
|
|
||||||
|
if (getSettingsStatus()) {
|
||||||
|
screen.addPreference(this);
|
||||||
|
addPreferences(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public abstract boolean getSettingsStatus();
|
||||||
|
|
||||||
|
public abstract void addPreferences(Context context);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,35 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings.preference.categories;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.preference.PreferenceScreen;
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
import app.revanced.extension.tiktok.settings.SettingsStatus;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.DownloadPathPreference;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.TogglePreference;
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public class DownloadsPreferenceCategory extends ConditionalPreferenceCategory {
|
||||||
|
public DownloadsPreferenceCategory(Context context, PreferenceScreen screen) {
|
||||||
|
super(context, screen);
|
||||||
|
setTitle("Downloads");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getSettingsStatus() {
|
||||||
|
return SettingsStatus.downloadEnabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addPreferences(Context context) {
|
||||||
|
addPreference(new DownloadPathPreference(
|
||||||
|
context,
|
||||||
|
"Download path",
|
||||||
|
Settings.DOWNLOAD_PATH
|
||||||
|
));
|
||||||
|
addPreference(new TogglePreference(
|
||||||
|
context,
|
||||||
|
"Remove watermark", "",
|
||||||
|
Settings.DOWNLOAD_WATERMARK
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings.preference.categories;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.preference.PreferenceScreen;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.settings.BaseSettings;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.TogglePreference;
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public class ExtensionPreferenceCategory extends ConditionalPreferenceCategory {
|
||||||
|
public ExtensionPreferenceCategory(Context context, PreferenceScreen screen) {
|
||||||
|
super(context, screen);
|
||||||
|
setTitle("Extension");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getSettingsStatus() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addPreferences(Context context) {
|
||||||
|
addPreference(new TogglePreference(context,
|
||||||
|
"Enable debug log",
|
||||||
|
"Show extension debug log.",
|
||||||
|
BaseSettings.DEBUG
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,55 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings.preference.categories;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.preference.PreferenceScreen;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.RangeValuePreference;
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
import app.revanced.extension.tiktok.settings.SettingsStatus;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.TogglePreference;
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public class FeedFilterPreferenceCategory extends ConditionalPreferenceCategory {
|
||||||
|
public FeedFilterPreferenceCategory(Context context, PreferenceScreen screen) {
|
||||||
|
super(context, screen);
|
||||||
|
setTitle("Feed filter");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getSettingsStatus() {
|
||||||
|
return SettingsStatus.feedFilterEnabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addPreferences(Context context) {
|
||||||
|
addPreference(new TogglePreference(
|
||||||
|
context,
|
||||||
|
"Remove feed ads", "Remove ads from feed.",
|
||||||
|
Settings.REMOVE_ADS
|
||||||
|
));
|
||||||
|
addPreference(new TogglePreference(
|
||||||
|
context,
|
||||||
|
"Hide livestreams", "Hide livestreams from feed.",
|
||||||
|
Settings.HIDE_LIVE
|
||||||
|
));
|
||||||
|
addPreference(new TogglePreference(
|
||||||
|
context,
|
||||||
|
"Hide story", "Hide story from feed.",
|
||||||
|
Settings.HIDE_STORY
|
||||||
|
));
|
||||||
|
addPreference(new TogglePreference(
|
||||||
|
context,
|
||||||
|
"Hide image video", "Hide image video from feed.",
|
||||||
|
Settings.HIDE_IMAGE
|
||||||
|
));
|
||||||
|
addPreference(new RangeValuePreference(
|
||||||
|
context,
|
||||||
|
"Min/Max views", "The minimum or maximum views of a video to show.",
|
||||||
|
Settings.MIN_MAX_VIEWS
|
||||||
|
));
|
||||||
|
addPreference(new RangeValuePreference(
|
||||||
|
context,
|
||||||
|
"Min/Max likes", "The minimum or maximum likes of a video to show.",
|
||||||
|
Settings.MIN_MAX_LIKES
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
package app.revanced.extension.tiktok.settings.preference.categories;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.preference.PreferenceScreen;
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
import app.revanced.extension.tiktok.settings.SettingsStatus;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.InputTextPreference;
|
||||||
|
import app.revanced.extension.tiktok.settings.preference.TogglePreference;
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
public class SimSpoofPreferenceCategory extends ConditionalPreferenceCategory {
|
||||||
|
public SimSpoofPreferenceCategory(Context context, PreferenceScreen screen) {
|
||||||
|
super(context, screen);
|
||||||
|
setTitle("Bypass regional restriction");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getSettingsStatus() {
|
||||||
|
return SettingsStatus.simSpoofEnabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addPreferences(Context context) {
|
||||||
|
addPreference(new TogglePreference(
|
||||||
|
context,
|
||||||
|
"Fake sim card info",
|
||||||
|
"Bypass regional restriction by fake sim card information.",
|
||||||
|
Settings.SIM_SPOOF
|
||||||
|
));
|
||||||
|
addPreference(new InputTextPreference(
|
||||||
|
context,
|
||||||
|
"Country ISO", "us, uk, jp, ...",
|
||||||
|
Settings.SIM_SPOOF_ISO
|
||||||
|
));
|
||||||
|
addPreference(new InputTextPreference(
|
||||||
|
context,
|
||||||
|
"Operator mcc+mnc", "mcc+mnc",
|
||||||
|
Settings.SIMSPOOF_MCCMNC
|
||||||
|
));
|
||||||
|
addPreference(new InputTextPreference(
|
||||||
|
context,
|
||||||
|
"Operator name", "Name of the operator.",
|
||||||
|
Settings.SIMSPOOF_OP_NAME
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package app.revanced.extension.tiktok.speed;
|
||||||
|
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
|
||||||
|
public class PlaybackSpeedPatch {
|
||||||
|
public static void rememberPlaybackSpeed(float newSpeed) {
|
||||||
|
Settings.REMEMBERED_SPEED.save(newSpeed);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static float getPlaybackSpeed() {
|
||||||
|
return Settings.REMEMBERED_SPEED.get();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,37 @@
|
|||||||
|
package app.revanced.extension.tiktok.spoof.sim;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.tiktok.settings.Settings;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class SpoofSimPatch {
|
||||||
|
|
||||||
|
private static final boolean ENABLED = Settings.SIM_SPOOF.get();
|
||||||
|
|
||||||
|
public static String getCountryIso(String value) {
|
||||||
|
if (ENABLED) {
|
||||||
|
String iso = Settings.SIM_SPOOF_ISO.get();
|
||||||
|
Logger.printDebug(() -> "Spoofing sim ISO from: " + value + " to: " + iso);
|
||||||
|
return iso;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getOperator(String value) {
|
||||||
|
if (ENABLED) {
|
||||||
|
String mcc_mnc = Settings.SIMSPOOF_MCCMNC.get();
|
||||||
|
Logger.printDebug(() -> "Spoofing sim MCC-MNC from: " + value + " to: " + mcc_mnc);
|
||||||
|
return mcc_mnc;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getOperatorName(String value) {
|
||||||
|
if (ENABLED) {
|
||||||
|
String operator = Settings.SIMSPOOF_OP_NAME.get();
|
||||||
|
Logger.printDebug(() -> "Spoofing sim operator from: " + value + " to: " + operator);
|
||||||
|
return operator;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package app.revanced.extension.tudortmund.lockscreen;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.hardware.display.DisplayManager;
|
||||||
|
import android.os.Build;
|
||||||
|
import android.view.Display;
|
||||||
|
import android.view.Window;
|
||||||
|
import androidx.appcompat.app.AppCompatActivity;
|
||||||
|
|
||||||
|
import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
|
||||||
|
import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
|
||||||
|
|
||||||
|
public class ShowOnLockscreenPatch {
|
||||||
|
/**
|
||||||
|
* @noinspection deprecation
|
||||||
|
*/
|
||||||
|
public static Window getWindow(AppCompatActivity activity, float brightness) {
|
||||||
|
Window window = activity.getWindow();
|
||||||
|
|
||||||
|
if (brightness >= 0) {
|
||||||
|
// High brightness set, therefore show on lockscreen.
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) activity.setShowWhenLocked(true);
|
||||||
|
else window.addFlags(FLAG_SHOW_WHEN_LOCKED | FLAG_DISMISS_KEYGUARD);
|
||||||
|
} else {
|
||||||
|
// Ignore brightness reset when the screen is turned off.
|
||||||
|
DisplayManager displayManager = (DisplayManager) activity.getSystemService(Context.DISPLAY_SERVICE);
|
||||||
|
|
||||||
|
boolean isScreenOn = false;
|
||||||
|
for (Display display : displayManager.getDisplays()) {
|
||||||
|
if (display.getState() == Display.STATE_OFF) continue;
|
||||||
|
|
||||||
|
isScreenOn = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isScreenOn) {
|
||||||
|
// Hide on lockscreen.
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) activity.setShowWhenLocked(false);
|
||||||
|
else window.clearFlags(FLAG_SHOW_WHEN_LOCKED | FLAG_DISMISS_KEYGUARD);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return window;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package app.revanced.extension.tumblr.patches;
|
||||||
|
|
||||||
|
import com.tumblr.rumblr.model.TimelineObject;
|
||||||
|
import com.tumblr.rumblr.model.Timelineable;
|
||||||
|
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public final class TimelineFilterPatch {
|
||||||
|
private static final HashSet<String> blockedObjectTypes = new HashSet<>();
|
||||||
|
|
||||||
|
static {
|
||||||
|
// This dummy gets removed by the TimelineFilterPatch and in its place,
|
||||||
|
// equivalent instructions with a different constant string
|
||||||
|
// will be inserted for each Timeline object type filter.
|
||||||
|
// Modifying this line may break the patch.
|
||||||
|
blockedObjectTypes.add("BLOCKED_OBJECT_DUMMY");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calls to this method are injected where the list of Timeline objects is first received.
|
||||||
|
// We modify the list filter out elements that we want to hide.
|
||||||
|
public static void filterTimeline(final List<TimelineObject<? extends Timelineable>> timelineObjects) {
|
||||||
|
final var iterator = timelineObjects.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
var timelineElement = iterator.next();
|
||||||
|
if (timelineElement == null) continue;
|
||||||
|
|
||||||
|
String elementType = timelineElement.getData().getTimelineObjectType().toString();
|
||||||
|
if (blockedObjectTypes.contains(elementType)) iterator.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package app.revanced.extension.twitch;
|
||||||
|
|
||||||
|
public class Utils {
|
||||||
|
|
||||||
|
/* Called from SettingsPatch smali */
|
||||||
|
public static int getStringId(String name) {
|
||||||
|
return app.revanced.extension.shared.Utils.getResourceIdentifier(name, "string");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Called from SettingsPatch smali */
|
||||||
|
public static int getDrawableId(String name) {
|
||||||
|
return app.revanced.extension.shared.Utils.getResourceIdentifier(name, "drawable");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package app.revanced.extension.twitch.adblock;
|
||||||
|
|
||||||
|
import okhttp3.Request;
|
||||||
|
|
||||||
|
public interface IAdblockService {
|
||||||
|
String friendlyName();
|
||||||
|
|
||||||
|
Integer maxAttempts();
|
||||||
|
|
||||||
|
Boolean isAvailable();
|
||||||
|
|
||||||
|
Request rewriteHlsRequest(Request originalRequest);
|
||||||
|
|
||||||
|
static boolean isVod(Request request){
|
||||||
|
return request.url().pathSegments().contains("vod");
|
||||||
|
}
|
||||||
|
|
||||||
|
static String channelName(Request request) {
|
||||||
|
for (String pathSegment : request.url().pathSegments()) {
|
||||||
|
if (pathSegment.endsWith(".m3u8")) {
|
||||||
|
return pathSegment.replace(".m3u8", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
package app.revanced.extension.twitch.adblock;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import okhttp3.HttpUrl;
|
||||||
|
import okhttp3.Request;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
|
||||||
|
public class LuminousService implements IAdblockService {
|
||||||
|
@Override
|
||||||
|
public String friendlyName() {
|
||||||
|
return str("revanced_proxy_luminous");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Integer maxAttempts() {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Boolean isAvailable() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Request rewriteHlsRequest(Request originalRequest) {
|
||||||
|
var type = IAdblockService.isVod(originalRequest) ? "vod" : "playlist";
|
||||||
|
var url = HttpUrl.parse("https://eu.luminous.dev/" +
|
||||||
|
type +
|
||||||
|
"/" +
|
||||||
|
IAdblockService.channelName(originalRequest) +
|
||||||
|
".m3u8" +
|
||||||
|
"%3Fallow_source%3Dtrue%26allow_audio_only%3Dtrue%26fast_bread%3Dtrue"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (url == null) {
|
||||||
|
Logger.printException(() -> "Failed to parse rewritten URL");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Overwrite old request
|
||||||
|
return new Request.Builder()
|
||||||
|
.get()
|
||||||
|
.url(url)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,96 @@
|
|||||||
|
package app.revanced.extension.twitch.adblock;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.twitch.api.RetrofitClient;
|
||||||
|
import okhttp3.HttpUrl;
|
||||||
|
import okhttp3.Request;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
|
||||||
|
public class PurpleAdblockService implements IAdblockService {
|
||||||
|
private final Map<String, Boolean> tunnels = new HashMap<>() {{
|
||||||
|
put("https://eu1.jupter.ga", false);
|
||||||
|
put("https://eu2.jupter.ga", false);
|
||||||
|
}};
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String friendlyName() {
|
||||||
|
return str("revanced_proxy_purpleadblock");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Integer maxAttempts() {
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Boolean isAvailable() {
|
||||||
|
for (String tunnel : tunnels.keySet()) {
|
||||||
|
var success = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
var response = RetrofitClient.getInstance().getPurpleAdblockApi().ping(tunnel).execute();
|
||||||
|
if (!response.isSuccessful()) {
|
||||||
|
Logger.printException(() ->
|
||||||
|
"PurpleAdBlock tunnel $tunnel returned an error: HTTP code " + response.code()
|
||||||
|
);
|
||||||
|
Logger.printDebug(response::message);
|
||||||
|
|
||||||
|
try (var errorBody = response.errorBody()) {
|
||||||
|
if (errorBody != null) {
|
||||||
|
Logger.printDebug(() -> {
|
||||||
|
try {
|
||||||
|
return errorBody.string();
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "PurpleAdBlock tunnel $tunnel is unavailable", ex);
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache availability data
|
||||||
|
tunnels.put(tunnel, success);
|
||||||
|
|
||||||
|
if (success)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Request rewriteHlsRequest(Request originalRequest) {
|
||||||
|
for (Map.Entry<String, Boolean> entry : tunnels.entrySet()) {
|
||||||
|
if (!entry.getValue()) continue;
|
||||||
|
|
||||||
|
var server = entry.getKey();
|
||||||
|
|
||||||
|
// Compose new URL
|
||||||
|
var url = HttpUrl.parse(server + "/channel/" + IAdblockService.channelName(originalRequest));
|
||||||
|
if (url == null) {
|
||||||
|
Logger.printException(() -> "Failed to parse rewritten URL");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Overwrite old request
|
||||||
|
return new Request.Builder()
|
||||||
|
.get()
|
||||||
|
.url(url)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.printException(() -> "No tunnels are available");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package app.revanced.extension.twitch.api;
|
||||||
|
|
||||||
|
import okhttp3.ResponseBody;
|
||||||
|
import retrofit2.Call;
|
||||||
|
import retrofit2.http.GET;
|
||||||
|
import retrofit2.http.Url;
|
||||||
|
|
||||||
|
/* only used for service pings */
|
||||||
|
public interface PurpleAdblockApi {
|
||||||
|
@GET /* root */
|
||||||
|
Call<ResponseBody> ping(@Url String baseUrl);
|
||||||
|
}
|
@ -0,0 +1,120 @@
|
|||||||
|
package app.revanced.extension.twitch.api;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
import app.revanced.extension.twitch.adblock.IAdblockService;
|
||||||
|
import app.revanced.extension.twitch.adblock.LuminousService;
|
||||||
|
import app.revanced.extension.twitch.adblock.PurpleAdblockService;
|
||||||
|
import app.revanced.extension.twitch.settings.Settings;
|
||||||
|
import okhttp3.Interceptor;
|
||||||
|
import okhttp3.Response;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
|
||||||
|
public class RequestInterceptor implements Interceptor {
|
||||||
|
private IAdblockService activeService = null;
|
||||||
|
|
||||||
|
private static final String PROXY_DISABLED = str("revanced_block_embedded_ads_entry_1");
|
||||||
|
private static final String LUMINOUS_SERVICE = str("revanced_block_embedded_ads_entry_2");
|
||||||
|
private static final String PURPLE_ADBLOCK_SERVICE = str("revanced_block_embedded_ads_entry_3");
|
||||||
|
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
public Response intercept(@NonNull Chain chain) throws IOException {
|
||||||
|
var originalRequest = chain.request();
|
||||||
|
|
||||||
|
if (Settings.BLOCK_EMBEDDED_ADS.get().equals(PROXY_DISABLED)) {
|
||||||
|
return chain.proceed(originalRequest);
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.printDebug(() -> "Intercepted request to URL:" + originalRequest.url());
|
||||||
|
|
||||||
|
// Skip if not HLS manifest request
|
||||||
|
if (!originalRequest.url().host().contains("usher.ttvnw.net")) {
|
||||||
|
return chain.proceed(originalRequest);
|
||||||
|
}
|
||||||
|
|
||||||
|
final String isVod;
|
||||||
|
if (IAdblockService.isVod(originalRequest)) isVod = "yes";
|
||||||
|
else isVod = "no";
|
||||||
|
|
||||||
|
Logger.printDebug(() -> "Found HLS manifest request. Is VOD? " +
|
||||||
|
isVod +
|
||||||
|
"; Channel: " +
|
||||||
|
IAdblockService.channelName(originalRequest)
|
||||||
|
);
|
||||||
|
|
||||||
|
// None of the services support VODs currently
|
||||||
|
if (IAdblockService.isVod(originalRequest)) return chain.proceed(originalRequest);
|
||||||
|
|
||||||
|
updateActiveService();
|
||||||
|
|
||||||
|
if (activeService != null) {
|
||||||
|
var available = activeService.isAvailable();
|
||||||
|
var rewritten = activeService.rewriteHlsRequest(originalRequest);
|
||||||
|
|
||||||
|
|
||||||
|
if (!available || rewritten == null) {
|
||||||
|
Utils.showToastShort(String.format(
|
||||||
|
str("revanced_embedded_ads_service_unavailable"), activeService.friendlyName()
|
||||||
|
));
|
||||||
|
return chain.proceed(originalRequest);
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.printDebug(() -> "Rewritten HLS stream URL: " + rewritten.url());
|
||||||
|
|
||||||
|
var maxAttempts = activeService.maxAttempts();
|
||||||
|
|
||||||
|
for (var i = 1; i <= maxAttempts; i++) {
|
||||||
|
// Execute rewritten request and close body to allow multiple proceed() calls
|
||||||
|
var response = chain.proceed(rewritten);
|
||||||
|
response.close();
|
||||||
|
|
||||||
|
if (!response.isSuccessful()) {
|
||||||
|
int attempt = i;
|
||||||
|
Logger.printException(() -> "Request failed (attempt " +
|
||||||
|
attempt +
|
||||||
|
"/" + maxAttempts + "): HTTP error " +
|
||||||
|
response.code() +
|
||||||
|
" (" + response.message() + ")"
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep(50);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Logger.printException(() -> "Failed to sleep", e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Accept response from ad blocker
|
||||||
|
Logger.printDebug(() -> "Ad-blocker used");
|
||||||
|
return chain.proceed(rewritten);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// maxAttempts exceeded; giving up on using the ad blocker
|
||||||
|
Utils.showToastLong(String.format(
|
||||||
|
str("revanced_embedded_ads_service_failed"),
|
||||||
|
activeService.friendlyName())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adblock disabled
|
||||||
|
return chain.proceed(originalRequest);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateActiveService() {
|
||||||
|
var current = Settings.BLOCK_EMBEDDED_ADS.get();
|
||||||
|
|
||||||
|
if (current.equals(LUMINOUS_SERVICE) && !(activeService instanceof LuminousService))
|
||||||
|
activeService = new LuminousService();
|
||||||
|
else if (current.equals(PURPLE_ADBLOCK_SERVICE) && !(activeService instanceof PurpleAdblockService))
|
||||||
|
activeService = new PurpleAdblockService();
|
||||||
|
else if (current.equals(PROXY_DISABLED))
|
||||||
|
activeService = null;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package app.revanced.extension.twitch.api;
|
||||||
|
|
||||||
|
import retrofit2.Retrofit;
|
||||||
|
|
||||||
|
public class RetrofitClient {
|
||||||
|
|
||||||
|
private static RetrofitClient instance = null;
|
||||||
|
private final PurpleAdblockApi purpleAdblockApi;
|
||||||
|
|
||||||
|
private RetrofitClient() {
|
||||||
|
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://localhost" /* dummy */).build();
|
||||||
|
purpleAdblockApi = retrofit.create(PurpleAdblockApi.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static synchronized RetrofitClient getInstance() {
|
||||||
|
if (instance == null) {
|
||||||
|
instance = new RetrofitClient();
|
||||||
|
}
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PurpleAdblockApi getPurpleAdblockApi() {
|
||||||
|
return purpleAdblockApi;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package app.revanced.extension.twitch.patches;
|
||||||
|
|
||||||
|
import app.revanced.extension.twitch.settings.Settings;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class AudioAdsPatch {
|
||||||
|
public static boolean shouldBlockAudioAds() {
|
||||||
|
return Settings.BLOCK_AUDIO_ADS.get();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package app.revanced.extension.twitch.patches;
|
||||||
|
|
||||||
|
import app.revanced.extension.twitch.settings.Settings;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class AutoClaimChannelPointsPatch {
|
||||||
|
public static boolean shouldAutoClaim() {
|
||||||
|
return Settings.AUTO_CLAIM_CHANNEL_POINTS.get();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package app.revanced.extension.twitch.patches;
|
||||||
|
|
||||||
|
import app.revanced.extension.twitch.settings.Settings;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class DebugModePatch {
|
||||||
|
public static boolean isDebugModeEnabled() {
|
||||||
|
return Settings.TWITCH_DEBUG_MODE.get();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package app.revanced.extension.twitch.patches;
|
||||||
|
|
||||||
|
import app.revanced.extension.twitch.api.RequestInterceptor;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class EmbeddedAdsPatch {
|
||||||
|
public static RequestInterceptor createRequestInterceptor() {
|
||||||
|
return new RequestInterceptor();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
package app.revanced.extension.twitch.patches;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
|
||||||
|
import android.graphics.Color;
|
||||||
|
import android.graphics.Typeface;
|
||||||
|
import android.text.SpannableStringBuilder;
|
||||||
|
import android.text.Spanned;
|
||||||
|
import android.text.SpannedString;
|
||||||
|
import android.text.style.ForegroundColorSpan;
|
||||||
|
import android.text.style.StrikethroughSpan;
|
||||||
|
import android.text.style.StyleSpan;
|
||||||
|
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import app.revanced.extension.twitch.settings.Settings;
|
||||||
|
import tv.twitch.android.shared.chat.util.ClickableUsernameSpan;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class ShowDeletedMessagesPatch {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injection point.
|
||||||
|
*/
|
||||||
|
public static boolean shouldUseSpoiler() {
|
||||||
|
return "spoiler".equals(Settings.SHOW_DELETED_MESSAGES.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean shouldCrossOut() {
|
||||||
|
return "cross-out".equals(Settings.SHOW_DELETED_MESSAGES.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
public static Spanned reformatDeletedMessage(Spanned original) {
|
||||||
|
if (!shouldCrossOut())
|
||||||
|
return null;
|
||||||
|
|
||||||
|
SpannableStringBuilder ssb = new SpannableStringBuilder(original);
|
||||||
|
ssb.setSpan(new StrikethroughSpan(), 0, original.length(), 0);
|
||||||
|
ssb.append(" (").append(str("revanced_deleted_msg")).append(")");
|
||||||
|
ssb.setSpan(new StyleSpan(Typeface.ITALIC), original.length(), ssb.length(), 0);
|
||||||
|
|
||||||
|
// Gray-out username
|
||||||
|
ClickableUsernameSpan[] usernameSpans = original.getSpans(0, original.length(), ClickableUsernameSpan.class);
|
||||||
|
if (usernameSpans.length > 0) {
|
||||||
|
ssb.setSpan(new ForegroundColorSpan(Color.parseColor("#ADADB8")), 0, original.getSpanEnd(usernameSpans[0]), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new SpannedString(ssb);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package app.revanced.extension.twitch.patches;
|
||||||
|
|
||||||
|
import app.revanced.extension.twitch.settings.Settings;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class VideoAdsPatch {
|
||||||
|
public static boolean shouldBlockVideoAds() {
|
||||||
|
return Settings.BLOCK_VIDEO_ADS.get();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,112 @@
|
|||||||
|
package app.revanced.extension.twitch.settings;
|
||||||
|
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.os.Bundle;
|
||||||
|
import androidx.appcompat.app.ActionBar;
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
import app.revanced.extension.twitch.settings.preference.ReVancedPreferenceFragment;
|
||||||
|
import tv.twitch.android.feature.settings.menu.SettingsMenuGroup;
|
||||||
|
import tv.twitch.android.settings.SettingsActivity;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hooks AppCompatActivity.
|
||||||
|
* <p>
|
||||||
|
* This class is responsible for injecting our own fragment by replacing the AppCompatActivity.
|
||||||
|
* @noinspection unused
|
||||||
|
*/
|
||||||
|
public class AppCompatActivityHook {
|
||||||
|
private static final int REVANCED_SETTINGS_MENU_ITEM_ID = 0x7;
|
||||||
|
private static final String EXTRA_REVANCED_SETTINGS = "app.revanced.twitch.settings";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Launches SettingsActivity and show ReVanced settings
|
||||||
|
*/
|
||||||
|
public static void startSettingsActivity() {
|
||||||
|
Logger.printDebug(() -> "Launching ReVanced settings");
|
||||||
|
|
||||||
|
final var context = Utils.getContext();
|
||||||
|
|
||||||
|
if (context != null) {
|
||||||
|
Intent intent = new Intent(context, SettingsActivity.class);
|
||||||
|
Bundle bundle = new Bundle();
|
||||||
|
bundle.putBoolean(EXTRA_REVANCED_SETTINGS, true);
|
||||||
|
intent.putExtras(bundle);
|
||||||
|
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||||
|
context.startActivity(intent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper for easy access in smali
|
||||||
|
* @return Returns string resource id
|
||||||
|
*/
|
||||||
|
public static int getReVancedSettingsString() {
|
||||||
|
return app.revanced.extension.twitch.Utils.getStringId("revanced_settings");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Intercepts settings menu group list creation in SettingsMenuPresenter$Event.MenuGroupsUpdated
|
||||||
|
* @return Returns a modified list of menu groups
|
||||||
|
*/
|
||||||
|
public static List<SettingsMenuGroup> handleSettingMenuCreation(List<SettingsMenuGroup> settingGroups, Object revancedEntry) {
|
||||||
|
List<SettingsMenuGroup> groups = new ArrayList<>(settingGroups);
|
||||||
|
|
||||||
|
if (groups.isEmpty()) {
|
||||||
|
// Create new menu group if none exist yet
|
||||||
|
List<Object> items = new ArrayList<>();
|
||||||
|
items.add(revancedEntry);
|
||||||
|
groups.add(new SettingsMenuGroup(items));
|
||||||
|
} else {
|
||||||
|
// Add to last menu group
|
||||||
|
int groupIdx = groups.size() - 1;
|
||||||
|
List<Object> items = new ArrayList<>(groups.remove(groupIdx).getSettingsMenuItems());
|
||||||
|
items.add(revancedEntry);
|
||||||
|
groups.add(new SettingsMenuGroup(items));
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.printDebug(() -> settingGroups.size() + " menu groups in list");
|
||||||
|
return groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Intercepts settings menu group onclick events
|
||||||
|
* @return Returns true if handled, otherwise false
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("rawtypes")
|
||||||
|
public static boolean handleSettingMenuOnClick(Enum item) {
|
||||||
|
Logger.printDebug(() -> "item " + item.ordinal() + " clicked");
|
||||||
|
if (item.ordinal() != REVANCED_SETTINGS_MENU_ITEM_ID) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
startSettingsActivity();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Intercepts fragment loading in SettingsActivity.onCreate
|
||||||
|
* @return Returns true if the revanced settings have been requested by the user, otherwise false
|
||||||
|
*/
|
||||||
|
public static boolean handleSettingsCreation(androidx.appcompat.app.AppCompatActivity base) {
|
||||||
|
if (!base.getIntent().getBooleanExtra(EXTRA_REVANCED_SETTINGS, false)) {
|
||||||
|
Logger.printDebug(() -> "Revanced settings not requested");
|
||||||
|
return false; // User wants to enter another settings fragment
|
||||||
|
}
|
||||||
|
Logger.printDebug(() -> "ReVanced settings requested");
|
||||||
|
|
||||||
|
ReVancedPreferenceFragment fragment = new ReVancedPreferenceFragment();
|
||||||
|
ActionBar supportActionBar = base.getSupportActionBar();
|
||||||
|
if (supportActionBar != null)
|
||||||
|
supportActionBar.setTitle(app.revanced.extension.twitch.Utils.getStringId("revanced_settings"));
|
||||||
|
|
||||||
|
base.getFragmentManager()
|
||||||
|
.beginTransaction()
|
||||||
|
.replace(Utils.getResourceIdentifier("fragment_container", "id"), fragment)
|
||||||
|
.commit();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package app.revanced.extension.twitch.settings;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.settings.BooleanSetting;
|
||||||
|
import app.revanced.extension.shared.settings.BaseSettings;
|
||||||
|
import app.revanced.extension.shared.settings.StringSetting;
|
||||||
|
|
||||||
|
import static java.lang.Boolean.FALSE;
|
||||||
|
import static java.lang.Boolean.TRUE;
|
||||||
|
|
||||||
|
public class Settings extends BaseSettings {
|
||||||
|
/* Ads */
|
||||||
|
public static final BooleanSetting BLOCK_VIDEO_ADS = new BooleanSetting("revanced_block_video_ads", TRUE);
|
||||||
|
public static final BooleanSetting BLOCK_AUDIO_ADS = new BooleanSetting("revanced_block_audio_ads", TRUE);
|
||||||
|
public static final StringSetting BLOCK_EMBEDDED_ADS = new StringSetting("revanced_block_embedded_ads", "luminous");
|
||||||
|
|
||||||
|
/* Chat */
|
||||||
|
public static final StringSetting SHOW_DELETED_MESSAGES = new StringSetting("revanced_show_deleted_messages", "cross-out");
|
||||||
|
public static final BooleanSetting AUTO_CLAIM_CHANNEL_POINTS = new BooleanSetting("revanced_auto_claim_channel_points", TRUE);
|
||||||
|
|
||||||
|
/* Misc */
|
||||||
|
/**
|
||||||
|
* Not to be confused with {@link BaseSettings#DEBUG}.
|
||||||
|
*/
|
||||||
|
public static final BooleanSetting TWITCH_DEBUG_MODE = new BooleanSetting("revanced_twitch_debug_mode", FALSE, true);
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package app.revanced.extension.twitch.settings.preference;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.graphics.Color;
|
||||||
|
import android.preference.PreferenceCategory;
|
||||||
|
import android.util.AttributeSet;
|
||||||
|
import android.view.View;
|
||||||
|
import android.widget.TextView;
|
||||||
|
|
||||||
|
public class CustomPreferenceCategory extends PreferenceCategory {
|
||||||
|
public CustomPreferenceCategory(Context context, AttributeSet attrs) {
|
||||||
|
super(context, attrs);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void onBindView(View rootView) {
|
||||||
|
super.onBindView(rootView);
|
||||||
|
|
||||||
|
if(rootView instanceof TextView) {
|
||||||
|
((TextView) rootView).setTextColor(Color.parseColor("#8161b3"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package app.revanced.extension.twitch.settings.preference;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.settings.preference.AbstractPreferenceFragment;
|
||||||
|
import app.revanced.extension.twitch.settings.Settings;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Preference fragment for ReVanced settings
|
||||||
|
*/
|
||||||
|
public class ReVancedPreferenceFragment extends AbstractPreferenceFragment {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void initialize() {
|
||||||
|
super.initialize();
|
||||||
|
|
||||||
|
// Do anything that forces this apps Settings bundle to load.
|
||||||
|
if (Settings.BLOCK_VIDEO_ADS.get()) {
|
||||||
|
Logger.printDebug(() -> "Block video ads enabled"); // Any statement that references the app settings.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
package app.revanced.extension.twitter.patches.hook.json
|
||||||
|
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
abstract class BaseJsonHook : JsonHook {
|
||||||
|
abstract fun apply(json: JSONObject)
|
||||||
|
|
||||||
|
override fun transform(json: JSONObject) = json.apply { apply(json) }
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package app.revanced.extension.twitter.patches.hook.json
|
||||||
|
|
||||||
|
import app.revanced.extension.twitter.patches.hook.patch.Hook
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
interface JsonHook : Hook<JSONObject> {
|
||||||
|
/**
|
||||||
|
* Transform a JSONObject.
|
||||||
|
*
|
||||||
|
* @param json The JSONObject.
|
||||||
|
*/
|
||||||
|
fun transform(json: JSONObject): JSONObject
|
||||||
|
|
||||||
|
override fun hook(type: JSONObject) = transform(type)
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package app.revanced.extension.twitter.patches.hook.json
|
||||||
|
|
||||||
|
import app.revanced.extension.twitter.patches.hook.patch.dummy.DummyHook
|
||||||
|
import app.revanced.extension.twitter.utils.json.JsonUtils.parseJson
|
||||||
|
import app.revanced.extension.twitter.utils.stream.StreamUtils
|
||||||
|
import org.json.JSONException
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStream
|
||||||
|
|
||||||
|
object JsonHookPatch {
|
||||||
|
// Additional hooks added by corresponding patch.
|
||||||
|
private val hooks = buildList<JsonHook> {
|
||||||
|
add(DummyHook)
|
||||||
|
}
|
||||||
|
|
||||||
|
@JvmStatic
|
||||||
|
fun parseJsonHook(jsonInputStream: InputStream): InputStream {
|
||||||
|
var jsonObject = try {
|
||||||
|
parseJson(jsonInputStream)
|
||||||
|
} catch (ignored: IOException) {
|
||||||
|
return jsonInputStream // Unreachable.
|
||||||
|
} catch (ignored: JSONException) {
|
||||||
|
return jsonInputStream
|
||||||
|
}
|
||||||
|
|
||||||
|
for (hook in hooks) jsonObject = hook.hook(jsonObject)
|
||||||
|
|
||||||
|
return StreamUtils.fromString(jsonObject.toString())
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,9 @@
|
|||||||
|
package app.revanced.extension.twitter.patches.hook.patch
|
||||||
|
|
||||||
|
interface Hook<T> {
|
||||||
|
/**
|
||||||
|
* Hook the given type.
|
||||||
|
* @param type The type to hook
|
||||||
|
*/
|
||||||
|
fun hook(type: T): T
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package app.revanced.extension.twitter.patches.hook.patch.ads
|
||||||
|
|
||||||
|
import app.revanced.extension.twitter.patches.hook.json.BaseJsonHook
|
||||||
|
import app.revanced.extension.twitter.patches.hook.twifucker.TwiFucker
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
object HideAdsHook : BaseJsonHook() {
|
||||||
|
/**
|
||||||
|
* Strips JSONObject from promoted ads.
|
||||||
|
*
|
||||||
|
* @param json The JSONObject.
|
||||||
|
*/
|
||||||
|
override fun apply(json: JSONObject) = TwiFucker.hidePromotedAds(json)
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package app.revanced.extension.twitter.patches.hook.patch.dummy
|
||||||
|
|
||||||
|
import app.revanced.extension.twitter.patches.hook.json.BaseJsonHook
|
||||||
|
import app.revanced.extension.twitter.patches.hook.json.JsonHookPatch
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dummy hook to reserve a register in [JsonHookPatch.hooks] list.
|
||||||
|
*/
|
||||||
|
object DummyHook : BaseJsonHook() {
|
||||||
|
override fun apply(json: JSONObject) {
|
||||||
|
// Do nothing.
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package app.revanced.extension.twitter.patches.hook.patch.recommendation
|
||||||
|
|
||||||
|
import app.revanced.extension.twitter.patches.hook.json.BaseJsonHook
|
||||||
|
import app.revanced.extension.twitter.patches.hook.twifucker.TwiFucker
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
object RecommendedUsersHook : BaseJsonHook() {
|
||||||
|
/**
|
||||||
|
* Strips JSONObject from recommended users.
|
||||||
|
*
|
||||||
|
* @param json The JSONObject.
|
||||||
|
*/
|
||||||
|
override fun apply(json: JSONObject) = TwiFucker.hideRecommendedUsers(json)
|
||||||
|
}
|
@ -0,0 +1,218 @@
|
|||||||
|
package app.revanced.extension.twitter.patches.hook.twifucker
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import app.revanced.extension.twitter.patches.hook.twifucker.TwiFuckerUtils.forEach
|
||||||
|
import app.revanced.extension.twitter.patches.hook.twifucker.TwiFuckerUtils.forEachIndexed
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
// https://raw.githubusercontent.com/Dr-TSNG/TwiFucker/880cdf1c1622e54ab45561ffcb4f53d94ed97bae/app/src/main/java/icu/nullptr/twifucker/hook/JsonHook.kt
|
||||||
|
internal object TwiFucker {
|
||||||
|
// root
|
||||||
|
private fun JSONObject.jsonGetInstructions(): JSONArray? = optJSONObject("timeline")?.optJSONArray("instructions")
|
||||||
|
|
||||||
|
private fun JSONObject.jsonGetData(): JSONObject? = optJSONObject("data")
|
||||||
|
|
||||||
|
private fun JSONObject.jsonHasRecommendedUsers(): Boolean = has("recommended_users")
|
||||||
|
|
||||||
|
private fun JSONObject.jsonRemoveRecommendedUsers() {
|
||||||
|
remove("recommended_users")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONObject.jsonCheckAndRemoveRecommendedUsers() {
|
||||||
|
if (jsonHasRecommendedUsers()) {
|
||||||
|
Log.d("ReVanced", "Handle recommended users: $this")
|
||||||
|
jsonRemoveRecommendedUsers()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONObject.jsonHasThreads(): Boolean = has("threads")
|
||||||
|
|
||||||
|
private fun JSONObject.jsonRemoveThreads() {
|
||||||
|
remove("threads")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONObject.jsonCheckAndRemoveThreads() {
|
||||||
|
if (jsonHasThreads()) {
|
||||||
|
Log.d("ReVanced", "Handle threads: $this")
|
||||||
|
jsonRemoveThreads()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// data
|
||||||
|
private fun JSONObject.dataGetInstructions(): JSONArray? {
|
||||||
|
val timeline =
|
||||||
|
optJSONObject("user_result")?.optJSONObject("result")
|
||||||
|
?.optJSONObject("timeline_response")?.optJSONObject("timeline")
|
||||||
|
?: optJSONObject("timeline_response")?.optJSONObject("timeline")
|
||||||
|
?: optJSONObject("search")?.optJSONObject("timeline_response")?.optJSONObject("timeline")
|
||||||
|
?: optJSONObject("timeline_response")
|
||||||
|
return timeline?.optJSONArray("instructions")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONObject.dataCheckAndRemove() {
|
||||||
|
dataGetInstructions()?.forEach { instruction ->
|
||||||
|
instruction.instructionCheckAndRemove { it.entriesRemoveAnnoyance() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONObject.dataGetLegacy(): JSONObject? =
|
||||||
|
optJSONObject("tweet_result")?.optJSONObject("result")?.let {
|
||||||
|
if (it.has("tweet")) {
|
||||||
|
it.optJSONObject("tweet")
|
||||||
|
} else {
|
||||||
|
it
|
||||||
|
}
|
||||||
|
}?.optJSONObject("legacy")
|
||||||
|
|
||||||
|
// entry
|
||||||
|
private fun JSONObject.entryHasPromotedMetadata(): Boolean =
|
||||||
|
optJSONObject("content")?.optJSONObject("item")?.optJSONObject("content")
|
||||||
|
?.optJSONObject("tweet")
|
||||||
|
?.has("promotedMetadata") == true || optJSONObject("content")?.optJSONObject("content")
|
||||||
|
?.has("tweetPromotedMetadata") == true || optJSONObject("item")?.optJSONObject("content")
|
||||||
|
?.has("tweetPromotedMetadata") == true
|
||||||
|
|
||||||
|
private fun JSONObject.entryGetContentItems(): JSONArray? =
|
||||||
|
optJSONObject("content")?.optJSONArray("items")
|
||||||
|
?: optJSONObject("content")?.optJSONObject("timelineModule")?.optJSONArray("items")
|
||||||
|
|
||||||
|
private fun JSONObject.entryIsTweetDetailRelatedTweets(): Boolean = optString("entryId").startsWith("tweetdetailrelatedtweets-")
|
||||||
|
|
||||||
|
private fun JSONObject.entryGetTrends(): JSONArray? = optJSONObject("content")?.optJSONObject("timelineModule")?.optJSONArray("items")
|
||||||
|
|
||||||
|
// trend
|
||||||
|
private fun JSONObject.trendHasPromotedMetadata(): Boolean =
|
||||||
|
optJSONObject("item")?.optJSONObject("content")?.optJSONObject("trend")
|
||||||
|
?.has("promotedMetadata") == true
|
||||||
|
|
||||||
|
private fun JSONArray.trendRemoveAds() {
|
||||||
|
val trendRemoveIndex = mutableListOf<Int>()
|
||||||
|
forEachIndexed { trendIndex, trend ->
|
||||||
|
if (trend.trendHasPromotedMetadata()) {
|
||||||
|
Log.d("ReVanced", "Handle trends ads $trendIndex $trend")
|
||||||
|
trendRemoveIndex.add(trendIndex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i in trendRemoveIndex.asReversed()) {
|
||||||
|
remove(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// instruction
|
||||||
|
private fun JSONObject.instructionTimelineAddEntries(): JSONArray? = optJSONArray("entries")
|
||||||
|
|
||||||
|
private fun JSONObject.instructionGetAddEntries(): JSONArray? = optJSONObject("addEntries")?.optJSONArray("entries")
|
||||||
|
|
||||||
|
private fun JSONObject.instructionCheckAndRemove(action: (JSONArray) -> Unit) {
|
||||||
|
instructionTimelineAddEntries()?.let(action)
|
||||||
|
instructionGetAddEntries()?.let(action)
|
||||||
|
}
|
||||||
|
|
||||||
|
// entries
|
||||||
|
private fun JSONArray.entriesRemoveTimelineAds() {
|
||||||
|
val removeIndex = mutableListOf<Int>()
|
||||||
|
forEachIndexed { entryIndex, entry ->
|
||||||
|
entry.entryGetTrends()?.trendRemoveAds()
|
||||||
|
|
||||||
|
if (entry.entryHasPromotedMetadata()) {
|
||||||
|
Log.d("ReVanced", "Handle timeline ads $entryIndex $entry")
|
||||||
|
removeIndex.add(entryIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
val innerRemoveIndex = mutableListOf<Int>()
|
||||||
|
val contentItems = entry.entryGetContentItems()
|
||||||
|
contentItems?.forEachIndexed inner@{ itemIndex, item ->
|
||||||
|
if (item.entryHasPromotedMetadata()) {
|
||||||
|
Log.d("ReVanced", "Handle timeline replies ads $entryIndex $entry")
|
||||||
|
if (contentItems.length() == 1) {
|
||||||
|
removeIndex.add(entryIndex)
|
||||||
|
} else {
|
||||||
|
innerRemoveIndex.add(itemIndex)
|
||||||
|
}
|
||||||
|
return@inner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i in innerRemoveIndex.asReversed()) {
|
||||||
|
contentItems?.remove(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i in removeIndex.reversed()) {
|
||||||
|
remove(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONArray.entriesRemoveTweetDetailRelatedTweets() {
|
||||||
|
val removeIndex = mutableListOf<Int>()
|
||||||
|
forEachIndexed { entryIndex, entry ->
|
||||||
|
|
||||||
|
if (entry.entryIsTweetDetailRelatedTweets()) {
|
||||||
|
Log.d("ReVanced", "Handle tweet detail related tweets $entryIndex $entry")
|
||||||
|
removeIndex.add(entryIndex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i in removeIndex.reversed()) {
|
||||||
|
remove(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONArray.entriesRemoveAnnoyance() {
|
||||||
|
entriesRemoveTimelineAds()
|
||||||
|
entriesRemoveTweetDetailRelatedTweets()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONObject.entryIsWhoToFollow(): Boolean =
|
||||||
|
optString("entryId").let {
|
||||||
|
it.startsWith("whoToFollow-") || it.startsWith("who-to-follow-") || it.startsWith("connect-module-")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONObject.itemContainsPromotedUser(): Boolean =
|
||||||
|
optJSONObject("item")?.optJSONObject("content")
|
||||||
|
?.has("userPromotedMetadata") == true || optJSONObject("item")?.optJSONObject("content")
|
||||||
|
?.optJSONObject("user")
|
||||||
|
?.has("userPromotedMetadata") == true || optJSONObject("item")?.optJSONObject("content")
|
||||||
|
?.optJSONObject("user")?.has("promotedMetadata") == true
|
||||||
|
|
||||||
|
fun JSONArray.entriesRemoveWhoToFollow() {
|
||||||
|
val entryRemoveIndex = mutableListOf<Int>()
|
||||||
|
forEachIndexed { entryIndex, entry ->
|
||||||
|
if (!entry.entryIsWhoToFollow()) return@forEachIndexed
|
||||||
|
|
||||||
|
Log.d("ReVanced", "Handle whoToFollow $entryIndex $entry")
|
||||||
|
entryRemoveIndex.add(entryIndex)
|
||||||
|
|
||||||
|
val items = entry.entryGetContentItems()
|
||||||
|
val userRemoveIndex = mutableListOf<Int>()
|
||||||
|
items?.forEachIndexed { index, item ->
|
||||||
|
item.itemContainsPromotedUser().let {
|
||||||
|
if (it) {
|
||||||
|
Log.d("ReVanced", "Handle whoToFollow promoted user $index $item")
|
||||||
|
userRemoveIndex.add(index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i in userRemoveIndex.reversed()) {
|
||||||
|
items?.remove(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i in entryRemoveIndex.reversed()) {
|
||||||
|
remove(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hideRecommendedUsers(json: JSONObject) {
|
||||||
|
json.filterInstructions { it.entriesRemoveWhoToFollow() }
|
||||||
|
json.jsonCheckAndRemoveRecommendedUsers()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hidePromotedAds(json: JSONObject) {
|
||||||
|
json.filterInstructions { it.entriesRemoveAnnoyance() }
|
||||||
|
json.jsonGetData()?.dataCheckAndRemove()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONObject.filterInstructions(action: (JSONArray) -> Unit) {
|
||||||
|
jsonGetInstructions()?.forEach { instruction ->
|
||||||
|
instruction.instructionCheckAndRemove(action)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package app.revanced.extension.twitter.patches.hook.twifucker
|
||||||
|
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
internal object TwiFuckerUtils {
|
||||||
|
inline fun JSONArray.forEach(action: (JSONObject) -> Unit) {
|
||||||
|
(0 until this.length()).forEach { i ->
|
||||||
|
if (this[i] is JSONObject) {
|
||||||
|
action(this[i] as JSONObject)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fun JSONArray.forEachIndexed(action: (index: Int, JSONObject) -> Unit) {
|
||||||
|
(0 until this.length()).forEach { i ->
|
||||||
|
if (this[i] is JSONObject) {
|
||||||
|
action(i, this[i] as JSONObject)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package app.revanced.extension.twitter.patches.links;
|
||||||
|
|
||||||
|
public final class ChangeLinkSharingDomainPatch {
|
||||||
|
private static final String DOMAIN_NAME = "https://fxtwitter.com";
|
||||||
|
private static final String LINK_FORMAT = "%s/%s/status/%s";
|
||||||
|
|
||||||
|
public static String formatResourceLink(Object... formatArgs) {
|
||||||
|
String username = (String) formatArgs[0];
|
||||||
|
String tweetId = (String) formatArgs[1];
|
||||||
|
return String.format(LINK_FORMAT, DOMAIN_NAME, username, tweetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String formatLink(long tweetId, String username) {
|
||||||
|
return String.format(LINK_FORMAT, DOMAIN_NAME, username, tweetId);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package app.revanced.extension.twitter.patches.links;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.util.Log;
|
||||||
|
|
||||||
|
public final class OpenLinksWithAppChooserPatch {
|
||||||
|
public static void openWithChooser(final Context context, final Intent intent) {
|
||||||
|
Log.d("ReVanced", "Opening intent with chooser: " + intent);
|
||||||
|
|
||||||
|
intent.setAction("android.intent.action.VIEW");
|
||||||
|
|
||||||
|
context.startActivity(Intent.createChooser(intent, null));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package app.revanced.extension.twitter.utils.json
|
||||||
|
|
||||||
|
import app.revanced.extension.twitter.utils.stream.StreamUtils
|
||||||
|
import org.json.JSONException
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStream
|
||||||
|
|
||||||
|
object JsonUtils {
|
||||||
|
@JvmStatic
|
||||||
|
@Throws(IOException::class, JSONException::class)
|
||||||
|
fun parseJson(jsonInputStream: InputStream) = JSONObject(StreamUtils.toString(jsonInputStream))
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package app.revanced.extension.twitter.utils.stream
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStream
|
||||||
|
|
||||||
|
object StreamUtils {
|
||||||
|
@Throws(IOException::class)
|
||||||
|
fun toString(inputStream: InputStream): String {
|
||||||
|
ByteArrayOutputStream().use { result ->
|
||||||
|
val buffer = ByteArray(1024)
|
||||||
|
var length: Int
|
||||||
|
while (inputStream.read(buffer).also { length = it } != -1) {
|
||||||
|
result.write(buffer, 0, length)
|
||||||
|
}
|
||||||
|
return result.toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun fromString(string: String): InputStream {
|
||||||
|
return ByteArrayInputStream(string.toByteArray())
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,45 @@
|
|||||||
|
package app.revanced.extension.youtube;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
public final class ByteTrieSearch extends TrieSearch<byte[]> {
|
||||||
|
|
||||||
|
private static final class ByteTrieNode extends TrieNode<byte[]> {
|
||||||
|
ByteTrieNode() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
ByteTrieNode(char nodeCharacterValue) {
|
||||||
|
super(nodeCharacterValue);
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
TrieNode<byte[]> createNode(char nodeCharacterValue) {
|
||||||
|
return new ByteTrieNode(nodeCharacterValue);
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
char getCharValue(byte[] text, int index) {
|
||||||
|
return (char) text[index];
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
int getTextLength(byte[] text) {
|
||||||
|
return text.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method for the common usage of converting Strings to raw UTF-8 bytes.
|
||||||
|
*/
|
||||||
|
public static byte[][] convertStringsToBytes(String... strings) {
|
||||||
|
final int length = strings.length;
|
||||||
|
byte[][] replacement = new byte[length][];
|
||||||
|
for (int i = 0; i < length; i++) {
|
||||||
|
replacement[i] = strings[i].getBytes(StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
return replacement;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ByteTrieSearch(@NonNull byte[]... patterns) {
|
||||||
|
super(new ByteTrieNode(), patterns);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package app.revanced.extension.youtube
|
||||||
|
|
||||||
|
/**
|
||||||
|
* generic event provider class
|
||||||
|
*/
|
||||||
|
class Event<T> {
|
||||||
|
private val eventListeners = mutableSetOf<(T) -> Unit>()
|
||||||
|
|
||||||
|
operator fun plusAssign(observer: (T) -> Unit) {
|
||||||
|
addObserver(observer)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addObserver(observer: (T) -> Unit) {
|
||||||
|
eventListeners.add(observer)
|
||||||
|
}
|
||||||
|
|
||||||
|
operator fun minusAssign(observer: (T) -> Unit) {
|
||||||
|
removeObserver(observer)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun removeObserver(observer: (T) -> Unit) {
|
||||||
|
eventListeners.remove(observer)
|
||||||
|
}
|
||||||
|
|
||||||
|
operator fun invoke(value: T) {
|
||||||
|
for (observer in eventListeners)
|
||||||
|
observer.invoke(value)
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package app.revanced.extension.youtube;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Text pattern searching using a prefix tree (trie).
|
||||||
|
*/
|
||||||
|
public final class StringTrieSearch extends TrieSearch<String> {
|
||||||
|
|
||||||
|
private static final class StringTrieNode extends TrieNode<String> {
|
||||||
|
StringTrieNode() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
StringTrieNode(char nodeCharacterValue) {
|
||||||
|
super(nodeCharacterValue);
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
TrieNode<String> createNode(char nodeValue) {
|
||||||
|
return new StringTrieNode(nodeValue);
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
char getCharValue(String text, int index) {
|
||||||
|
return text.charAt(index);
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
int getTextLength(String text) {
|
||||||
|
return text.length();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public StringTrieSearch(@NonNull String... patterns) {
|
||||||
|
super(new StringTrieNode(), patterns);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,85 @@
|
|||||||
|
package app.revanced.extension.youtube;
|
||||||
|
|
||||||
|
import android.app.Activity;
|
||||||
|
import android.graphics.Color;
|
||||||
|
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
|
||||||
|
public class ThemeHelper {
|
||||||
|
@Nullable
|
||||||
|
private static Integer darkThemeColor, lightThemeColor;
|
||||||
|
private static int themeValue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injection point.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public static void setTheme(Enum<?> value) {
|
||||||
|
final int newOrdinalValue = value.ordinal();
|
||||||
|
if (themeValue != newOrdinalValue) {
|
||||||
|
themeValue = newOrdinalValue;
|
||||||
|
Logger.printDebug(() -> "Theme value: " + newOrdinalValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isDarkTheme() {
|
||||||
|
return themeValue == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void setActivityTheme(Activity activity) {
|
||||||
|
final var theme = isDarkTheme()
|
||||||
|
? "Theme.YouTube.Settings.Dark"
|
||||||
|
: "Theme.YouTube.Settings";
|
||||||
|
activity.setTheme(Utils.getResourceIdentifier(theme, "style"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injection point.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("SameReturnValue")
|
||||||
|
private static String darkThemeResourceName() {
|
||||||
|
// Value is changed by Theme patch, if included.
|
||||||
|
return "@color/yt_black3";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return The dark theme color as specified by the Theme patch (if included),
|
||||||
|
* or the dark mode background color unpatched YT uses.
|
||||||
|
*/
|
||||||
|
public static int getDarkThemeColor() {
|
||||||
|
if (darkThemeColor == null) {
|
||||||
|
darkThemeColor = getColorInt(darkThemeResourceName());
|
||||||
|
}
|
||||||
|
return darkThemeColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injection point.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("SameReturnValue")
|
||||||
|
private static String lightThemeResourceName() {
|
||||||
|
// Value is changed by Theme patch, if included.
|
||||||
|
return "@color/yt_white1";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return The light theme color as specified by the Theme patch (if included),
|
||||||
|
* or the non dark mode background color unpatched YT uses.
|
||||||
|
*/
|
||||||
|
public static int getLightThemeColor() {
|
||||||
|
if (lightThemeColor == null) {
|
||||||
|
lightThemeColor = getColorInt(lightThemeResourceName());
|
||||||
|
}
|
||||||
|
return lightThemeColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int getColorInt(String colorString) {
|
||||||
|
if (colorString.startsWith("#")) {
|
||||||
|
return Color.parseColor(colorString);
|
||||||
|
}
|
||||||
|
return Utils.getResourceColor(colorString);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,412 @@
|
|||||||
|
package app.revanced.extension.youtube;
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Searches for a group of different patterns using a trie (prefix tree).
|
||||||
|
* Can significantly speed up searching for multiple patterns.
|
||||||
|
*/
|
||||||
|
public abstract class TrieSearch<T> {
|
||||||
|
|
||||||
|
public interface TriePatternMatchedCallback<T> {
|
||||||
|
/**
|
||||||
|
* Called when a pattern is matched.
|
||||||
|
*
|
||||||
|
* @param textSearched Text that was searched.
|
||||||
|
* @param matchedStartIndex Start index of the search text, where the pattern was matched.
|
||||||
|
* @param matchedLength Length of the match.
|
||||||
|
* @param callbackParameter Optional parameter passed into {@link TrieSearch#matches(Object, Object)}.
|
||||||
|
* @return True, if the search should stop here.
|
||||||
|
* If false, searching will continue to look for other matches.
|
||||||
|
*/
|
||||||
|
boolean patternMatched(T textSearched, int matchedStartIndex, int matchedLength, Object callbackParameter);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a compressed tree path for a single pattern that shares no sibling nodes.
|
||||||
|
*
|
||||||
|
* For example, if a tree contains the patterns: "foobar", "football", "feet",
|
||||||
|
* it would contain 3 compressed paths of: "bar", "tball", "eet".
|
||||||
|
*
|
||||||
|
* And the tree would contain children arrays only for the first level containing 'f',
|
||||||
|
* the second level containing 'o',
|
||||||
|
* and the third level containing 'o'.
|
||||||
|
*
|
||||||
|
* This is done to reduce memory usage, which can be substantial if many long patterns are used.
|
||||||
|
*/
|
||||||
|
private static final class TrieCompressedPath<T> {
|
||||||
|
final T pattern;
|
||||||
|
final int patternStartIndex;
|
||||||
|
final int patternLength;
|
||||||
|
final TriePatternMatchedCallback<T> callback;
|
||||||
|
|
||||||
|
TrieCompressedPath(T pattern, int patternStartIndex, int patternLength, TriePatternMatchedCallback<T> callback) {
|
||||||
|
this.pattern = pattern;
|
||||||
|
this.patternStartIndex = patternStartIndex;
|
||||||
|
this.patternLength = patternLength;
|
||||||
|
this.callback = callback;
|
||||||
|
}
|
||||||
|
boolean matches(TrieNode<T> enclosingNode, // Used only for the get character method.
|
||||||
|
T searchText, int searchTextLength, int searchTextIndex, Object callbackParameter) {
|
||||||
|
if (searchTextLength - searchTextIndex < patternLength - patternStartIndex) {
|
||||||
|
return false; // Remaining search text is shorter than the remaining leaf pattern and they cannot match.
|
||||||
|
}
|
||||||
|
for (int i = searchTextIndex, j = patternStartIndex; j < patternLength; i++, j++) {
|
||||||
|
if (enclosingNode.getCharValue(searchText, i) != enclosingNode.getCharValue(pattern, j)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return callback == null || callback.patternMatched(searchText,
|
||||||
|
searchTextIndex - patternStartIndex, patternLength, callbackParameter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static abstract class TrieNode<T> {
|
||||||
|
/**
|
||||||
|
* Dummy value used for root node. Value can be anything as it's never referenced.
|
||||||
|
*/
|
||||||
|
private static final char ROOT_NODE_CHARACTER_VALUE = 0; // ASCII null character.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How much to expand the children array when resizing.
|
||||||
|
*/
|
||||||
|
private static final int CHILDREN_ARRAY_INCREASE_SIZE_INCREMENT = 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Character this node represents.
|
||||||
|
* This field is ignored for the root node (which does not represent any character).
|
||||||
|
*/
|
||||||
|
private final char nodeValue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A compressed graph path that represents the remaining pattern characters of a single child node.
|
||||||
|
*
|
||||||
|
* If present then child array is always null, although callbacks for other
|
||||||
|
* end of patterns can also exist on this same node.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private TrieCompressedPath<T> leaf;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* All child nodes. Only present if no compressed leaf exist.
|
||||||
|
*
|
||||||
|
* Array is dynamically increased in size as needed,
|
||||||
|
* and uses perfect hashing for the elements it contains.
|
||||||
|
*
|
||||||
|
* So if the array contains a given character,
|
||||||
|
* the character will always map to the node with index: (character % arraySize).
|
||||||
|
*
|
||||||
|
* Elements not contained can collide with elements the array does contain,
|
||||||
|
* so must compare the nodes character value.
|
||||||
|
*
|
||||||
|
* Alternatively this array could be a sorted and densely packed array,
|
||||||
|
* and lookup is done using binary search.
|
||||||
|
* That would save a small amount of memory because there's no null children entries,
|
||||||
|
* but would give a worst case search of O(nlog(m)) where n is the number of
|
||||||
|
* characters in the searched text and m is the maximum size of the sorted character arrays.
|
||||||
|
* Using a hash table array always gives O(n) search time.
|
||||||
|
* The memory usage here is very small (all Litho filters use ~10KB of memory),
|
||||||
|
* so the more performant hash implementation is chosen.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private TrieNode<T>[] children;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Callbacks for all patterns that end at this node.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private List<TriePatternMatchedCallback<T>> endOfPatternCallback;
|
||||||
|
|
||||||
|
TrieNode() {
|
||||||
|
this.nodeValue = ROOT_NODE_CHARACTER_VALUE;
|
||||||
|
}
|
||||||
|
TrieNode(char nodeCharacterValue) {
|
||||||
|
this.nodeValue = nodeCharacterValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param pattern Pattern to add.
|
||||||
|
* @param patternIndex Current recursive index of the pattern.
|
||||||
|
* @param patternLength Length of the pattern.
|
||||||
|
* @param callback Callback, where a value of NULL indicates to always accept a pattern match.
|
||||||
|
*/
|
||||||
|
private void addPattern(@NonNull T pattern, int patternIndex, int patternLength,
|
||||||
|
@Nullable TriePatternMatchedCallback<T> callback) {
|
||||||
|
if (patternIndex == patternLength) { // Reached the end of the pattern.
|
||||||
|
if (endOfPatternCallback == null) {
|
||||||
|
endOfPatternCallback = new ArrayList<>(1);
|
||||||
|
}
|
||||||
|
endOfPatternCallback.add(callback);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (leaf != null) {
|
||||||
|
// Reached end of the graph and a leaf exist.
|
||||||
|
// Recursively call back into this method and push the existing leaf down 1 level.
|
||||||
|
if (children != null) throw new IllegalStateException();
|
||||||
|
//noinspection unchecked
|
||||||
|
children = new TrieNode[1];
|
||||||
|
TrieCompressedPath<T> temp = leaf;
|
||||||
|
leaf = null;
|
||||||
|
addPattern(temp.pattern, temp.patternStartIndex, temp.patternLength, temp.callback);
|
||||||
|
// Continue onward and add the parameter pattern.
|
||||||
|
} else if (children == null) {
|
||||||
|
leaf = new TrieCompressedPath<>(pattern, patternIndex, patternLength, callback);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final char character = getCharValue(pattern, patternIndex);
|
||||||
|
final int arrayIndex = hashIndexForTableSize(children.length, character);
|
||||||
|
TrieNode<T> child = children[arrayIndex];
|
||||||
|
if (child == null) {
|
||||||
|
child = createNode(character);
|
||||||
|
children[arrayIndex] = child;
|
||||||
|
} else if (child.nodeValue != character) {
|
||||||
|
// Hash collision. Resize the table until perfect hashing is found.
|
||||||
|
child = createNode(character);
|
||||||
|
expandChildArray(child);
|
||||||
|
}
|
||||||
|
child.addPattern(pattern, patternIndex + 1, patternLength, callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resizes the children table until all nodes hash to exactly one array index.
|
||||||
|
*/
|
||||||
|
private void expandChildArray(TrieNode<T> child) {
|
||||||
|
int replacementArraySize = Objects.requireNonNull(children).length;
|
||||||
|
while (true) {
|
||||||
|
replacementArraySize += CHILDREN_ARRAY_INCREASE_SIZE_INCREMENT;
|
||||||
|
//noinspection unchecked
|
||||||
|
TrieNode<T>[] replacement = new TrieNode[replacementArraySize];
|
||||||
|
addNodeToArray(replacement, child);
|
||||||
|
boolean collision = false;
|
||||||
|
for (TrieNode<T> existingChild : children) {
|
||||||
|
if (existingChild != null) {
|
||||||
|
if (!addNodeToArray(replacement, existingChild)) {
|
||||||
|
collision = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (collision) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
children = replacement;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <T> boolean addNodeToArray(TrieNode<T>[] array, TrieNode<T> childToAdd) {
|
||||||
|
final int insertIndex = hashIndexForTableSize(array.length, childToAdd.nodeValue);
|
||||||
|
if (array[insertIndex] != null ) {
|
||||||
|
return false; // Collision.
|
||||||
|
}
|
||||||
|
array[insertIndex] = childToAdd;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int hashIndexForTableSize(int arraySize, char nodeValue) {
|
||||||
|
return nodeValue % arraySize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method is static and uses a loop to avoid all recursion.
|
||||||
|
* This is done for performance since the JVM does not optimize tail recursion.
|
||||||
|
*
|
||||||
|
* @param startNode Node to start the search from.
|
||||||
|
* @param searchText Text to search for patterns in.
|
||||||
|
* @param searchTextIndex Start index, inclusive.
|
||||||
|
* @param searchTextEndIndex End index, exclusive.
|
||||||
|
* @return If any pattern matches, and it's associated callback halted the search.
|
||||||
|
*/
|
||||||
|
private static <T> boolean matches(final TrieNode<T> startNode, final T searchText,
|
||||||
|
int searchTextIndex, final int searchTextEndIndex,
|
||||||
|
final Object callbackParameter) {
|
||||||
|
TrieNode<T> node = startNode;
|
||||||
|
int currentMatchLength = 0;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
TrieCompressedPath<T> leaf = node.leaf;
|
||||||
|
if (leaf != null && leaf.matches(startNode, searchText, searchTextEndIndex, searchTextIndex, callbackParameter)) {
|
||||||
|
return true; // Leaf exists and it matched the search text.
|
||||||
|
}
|
||||||
|
List<TriePatternMatchedCallback<T>> endOfPatternCallback = node.endOfPatternCallback;
|
||||||
|
if (endOfPatternCallback != null) {
|
||||||
|
final int matchStartIndex = searchTextIndex - currentMatchLength;
|
||||||
|
for (@Nullable TriePatternMatchedCallback<T> callback : endOfPatternCallback) {
|
||||||
|
if (callback == null) {
|
||||||
|
return true; // No callback and all matches are valid.
|
||||||
|
}
|
||||||
|
if (callback.patternMatched(searchText, matchStartIndex, currentMatchLength, callbackParameter)) {
|
||||||
|
return true; // Callback confirmed the match.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TrieNode<T>[] children = node.children;
|
||||||
|
if (children == null) {
|
||||||
|
return false; // Reached a graph end point and there's no further patterns to search.
|
||||||
|
}
|
||||||
|
if (searchTextIndex == searchTextEndIndex) {
|
||||||
|
return false; // Reached end of the search text and found no matches.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use the start node to reduce VM method lookup, since all nodes are the same class type.
|
||||||
|
final char character = startNode.getCharValue(searchText, searchTextIndex);
|
||||||
|
final int arrayIndex = hashIndexForTableSize(children.length, character);
|
||||||
|
TrieNode<T> child = children[arrayIndex];
|
||||||
|
if (child == null || child.nodeValue != character) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
node = child;
|
||||||
|
searchTextIndex++;
|
||||||
|
currentMatchLength++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gives an approximate memory usage.
|
||||||
|
*
|
||||||
|
* @return Estimated number of memory pointers used, starting from this node and including all children.
|
||||||
|
*/
|
||||||
|
private int estimatedNumberOfPointersUsed() {
|
||||||
|
int numberOfPointers = 4; // Number of fields in this class.
|
||||||
|
if (leaf != null) {
|
||||||
|
numberOfPointers += 4; // Number of fields in leaf node.
|
||||||
|
}
|
||||||
|
if (endOfPatternCallback != null) {
|
||||||
|
numberOfPointers += endOfPatternCallback.size();
|
||||||
|
}
|
||||||
|
if (children != null) {
|
||||||
|
numberOfPointers += children.length;
|
||||||
|
for (TrieNode<T> child : children) {
|
||||||
|
if (child != null) {
|
||||||
|
numberOfPointers += child.estimatedNumberOfPointersUsed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return numberOfPointers;
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract TrieNode<T> createNode(char nodeValue);
|
||||||
|
abstract char getCharValue(T text, int index);
|
||||||
|
abstract int getTextLength(T text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Root node, and it's children represent the first pattern characters.
|
||||||
|
*/
|
||||||
|
private final TrieNode<T> root;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Patterns to match.
|
||||||
|
*/
|
||||||
|
private final List<T> patterns = new ArrayList<>();
|
||||||
|
|
||||||
|
@SafeVarargs
|
||||||
|
TrieSearch(@NonNull TrieNode<T> root, @NonNull T... patterns) {
|
||||||
|
this.root = Objects.requireNonNull(root);
|
||||||
|
addPatterns(patterns);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SafeVarargs
|
||||||
|
public final void addPatterns(@NonNull T... patterns) {
|
||||||
|
for (T pattern : patterns) {
|
||||||
|
addPattern(pattern);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a pattern that will always return a positive match if found.
|
||||||
|
*
|
||||||
|
* @param pattern Pattern to add. Calling this with a zero length pattern does nothing.
|
||||||
|
*/
|
||||||
|
public void addPattern(@NonNull T pattern) {
|
||||||
|
addPattern(pattern, root.getTextLength(pattern), null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param pattern Pattern to add. Calling this with a zero length pattern does nothing.
|
||||||
|
* @param callback Callback to determine if searching should halt when a match is found.
|
||||||
|
*/
|
||||||
|
public void addPattern(@NonNull T pattern, @NonNull TriePatternMatchedCallback<T> callback) {
|
||||||
|
addPattern(pattern, root.getTextLength(pattern), Objects.requireNonNull(callback));
|
||||||
|
}
|
||||||
|
|
||||||
|
void addPattern(@NonNull T pattern, int patternLength, @Nullable TriePatternMatchedCallback<T> callback) {
|
||||||
|
if (patternLength == 0) return; // Nothing to match
|
||||||
|
|
||||||
|
patterns.add(pattern);
|
||||||
|
root.addPattern(pattern, 0, patternLength, callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final boolean matches(@NonNull T textToSearch) {
|
||||||
|
return matches(textToSearch, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean matches(@NonNull T textToSearch, @NonNull Object callbackParameter) {
|
||||||
|
return matches(textToSearch, 0, root.getTextLength(textToSearch),
|
||||||
|
Objects.requireNonNull(callbackParameter));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean matches(@NonNull T textToSearch, int startIndex) {
|
||||||
|
return matches(textToSearch, startIndex, root.getTextLength(textToSearch));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final boolean matches(@NonNull T textToSearch, int startIndex, int endIndex) {
|
||||||
|
return matches(textToSearch, startIndex, endIndex, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Searches through text, looking for any substring that matches any pattern in this tree.
|
||||||
|
*
|
||||||
|
* @param textToSearch Text to search through.
|
||||||
|
* @param startIndex Index to start searching, inclusive value.
|
||||||
|
* @param endIndex Index to stop matching, exclusive value.
|
||||||
|
* @param callbackParameter Optional parameter passed to the callbacks.
|
||||||
|
* @return If any pattern matched, and it's callback halted searching.
|
||||||
|
*/
|
||||||
|
public boolean matches(@NonNull T textToSearch, int startIndex, int endIndex, @Nullable Object callbackParameter) {
|
||||||
|
return matches(textToSearch, root.getTextLength(textToSearch), startIndex, endIndex, callbackParameter);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean matches(@NonNull T textToSearch, int textToSearchLength, int startIndex, int endIndex,
|
||||||
|
@Nullable Object callbackParameter) {
|
||||||
|
if (endIndex > textToSearchLength) {
|
||||||
|
throw new IllegalArgumentException("endIndex: " + endIndex
|
||||||
|
+ " is greater than texToSearchLength: " + textToSearchLength);
|
||||||
|
}
|
||||||
|
if (patterns.isEmpty()) {
|
||||||
|
return false; // No patterns were added.
|
||||||
|
}
|
||||||
|
for (int i = startIndex; i < endIndex; i++) {
|
||||||
|
if (TrieNode.matches(root, textToSearch, i, endIndex, callbackParameter)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return Estimated memory size (in kilobytes) of this instance.
|
||||||
|
*/
|
||||||
|
public int getEstimatedMemorySize() {
|
||||||
|
if (patterns.isEmpty()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
// Assume the device has less than 32GB of ram (and can use pointer compression),
|
||||||
|
// or the device is 32-bit.
|
||||||
|
final int numberOfBytesPerPointer = 4;
|
||||||
|
return (int) Math.ceil((numberOfBytesPerPointer * root.estimatedNumberOfPointersUsed()) / 1024.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int numberOfPatterns() {
|
||||||
|
return patterns.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<T> getPatterns() {
|
||||||
|
return Collections.unmodifiableList(patterns);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,710 @@
|
|||||||
|
package app.revanced.extension.youtube.patches;
|
||||||
|
|
||||||
|
import static app.revanced.extension.shared.StringRef.str;
|
||||||
|
import static app.revanced.extension.youtube.settings.Settings.*;
|
||||||
|
import static app.revanced.extension.youtube.shared.NavigationBar.NavigationButton;
|
||||||
|
|
||||||
|
import android.net.Uri;
|
||||||
|
|
||||||
|
import androidx.annotation.GuardedBy;
|
||||||
|
import androidx.annotation.NonNull;
|
||||||
|
import androidx.annotation.Nullable;
|
||||||
|
|
||||||
|
import org.chromium.net.UrlRequest;
|
||||||
|
import org.chromium.net.UrlResponseInfo;
|
||||||
|
import org.chromium.net.impl.CronetUrlRequest;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
import app.revanced.extension.shared.Logger;
|
||||||
|
import app.revanced.extension.shared.Utils;
|
||||||
|
import app.revanced.extension.shared.settings.Setting;
|
||||||
|
import app.revanced.extension.youtube.settings.Settings;
|
||||||
|
import app.revanced.extension.youtube.shared.NavigationBar;
|
||||||
|
import app.revanced.extension.youtube.shared.PlayerType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Alternative YouTube thumbnails.
|
||||||
|
* <p>
|
||||||
|
* Can show YouTube provided screen captures of beginning/middle/end of the video.
|
||||||
|
* (ie: sd1.jpg, sd2.jpg, sd3.jpg).
|
||||||
|
* <p>
|
||||||
|
* Or can show crowd-sourced thumbnails provided by DeArrow (<a href="http://dearrow.ajay.app">...</a>).
|
||||||
|
* <p>
|
||||||
|
* Or can use DeArrow and fall back to screen captures if DeArrow is not available.
|
||||||
|
* <p>
|
||||||
|
* Has an additional option to use 'fast' video still thumbnails,
|
||||||
|
* where it forces sd thumbnail quality and skips verifying if the alt thumbnail image exists.
|
||||||
|
* The UI loading time will be the same or better than using original thumbnails,
|
||||||
|
* but thumbnails will initially fail to load for all live streams, unreleased, and occasionally very old videos.
|
||||||
|
* If a failed thumbnail load is reloaded (ie: scroll off, then on screen), then the original thumbnail
|
||||||
|
* is reloaded instead. Fast thumbnails requires using SD or lower thumbnail resolution,
|
||||||
|
* because a noticeable number of videos do not have hq720 and too much fail to load.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public final class AlternativeThumbnailsPatch {
|
||||||
|
|
||||||
|
// These must be class declarations if declared here,
|
||||||
|
// otherwise the app will not load due to cyclic initialization errors.
|
||||||
|
public static final class DeArrowAvailability implements Setting.Availability {
|
||||||
|
public static boolean usingDeArrowAnywhere() {
|
||||||
|
return ALT_THUMBNAIL_HOME.get().useDeArrow
|
||||||
|
|| ALT_THUMBNAIL_SUBSCRIPTIONS.get().useDeArrow
|
||||||
|
|| ALT_THUMBNAIL_LIBRARY.get().useDeArrow
|
||||||
|
|| ALT_THUMBNAIL_PLAYER.get().useDeArrow
|
||||||
|
|| ALT_THUMBNAIL_SEARCH.get().useDeArrow;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isAvailable() {
|
||||||
|
return usingDeArrowAnywhere();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final class StillImagesAvailability implements Setting.Availability {
|
||||||
|
public static boolean usingStillImagesAnywhere() {
|
||||||
|
return ALT_THUMBNAIL_HOME.get().useStillImages
|
||||||
|
|| ALT_THUMBNAIL_SUBSCRIPTIONS.get().useStillImages
|
||||||
|
|| ALT_THUMBNAIL_LIBRARY.get().useStillImages
|
||||||
|
|| ALT_THUMBNAIL_PLAYER.get().useStillImages
|
||||||
|
|| ALT_THUMBNAIL_SEARCH.get().useStillImages;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isAvailable() {
|
||||||
|
return usingStillImagesAnywhere();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum ThumbnailOption {
|
||||||
|
ORIGINAL(false, false),
|
||||||
|
DEARROW(true, false),
|
||||||
|
DEARROW_STILL_IMAGES(true, true),
|
||||||
|
STILL_IMAGES(false, true);
|
||||||
|
|
||||||
|
final boolean useDeArrow;
|
||||||
|
final boolean useStillImages;
|
||||||
|
|
||||||
|
ThumbnailOption(boolean useDeArrow, boolean useStillImages) {
|
||||||
|
this.useDeArrow = useDeArrow;
|
||||||
|
this.useStillImages = useStillImages;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum ThumbnailStillTime {
|
||||||
|
BEGINNING(1),
|
||||||
|
MIDDLE(2),
|
||||||
|
END(3);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The url alt image number. Such as the 2 in 'hq720_2.jpg'
|
||||||
|
*/
|
||||||
|
final int altImageNumber;
|
||||||
|
|
||||||
|
ThumbnailStillTime(int altImageNumber) {
|
||||||
|
this.altImageNumber = altImageNumber;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final Uri dearrowApiUri;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The scheme and host of {@link #dearrowApiUri}.
|
||||||
|
*/
|
||||||
|
private static final String deArrowApiUrlPrefix;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How long to temporarily turn off DeArrow if it fails for any reason.
|
||||||
|
*/
|
||||||
|
private static final long DEARROW_FAILURE_API_BACKOFF_MILLISECONDS = 5 * 60 * 1000; // 5 Minutes.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If non zero, then the system time of when DeArrow API calls can resume.
|
||||||
|
*/
|
||||||
|
private static volatile long timeToResumeDeArrowAPICalls;
|
||||||
|
|
||||||
|
static {
|
||||||
|
dearrowApiUri = validateSettings();
|
||||||
|
final int port = dearrowApiUri.getPort();
|
||||||
|
String portString = port == -1 ? "" : (":" + port);
|
||||||
|
deArrowApiUrlPrefix = dearrowApiUri.getScheme() + "://" + dearrowApiUri.getHost() + portString + "/";
|
||||||
|
Logger.printDebug(() -> "Using DeArrow API address: " + deArrowApiUrlPrefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fix any bad imported data.
|
||||||
|
*/
|
||||||
|
private static Uri validateSettings() {
|
||||||
|
Uri apiUri = Uri.parse(Settings.ALT_THUMBNAIL_DEARROW_API_URL.get());
|
||||||
|
// Cannot use unsecured 'http', otherwise the connections fail to start and no callbacks hooks are made.
|
||||||
|
String scheme = apiUri.getScheme();
|
||||||
|
if (scheme == null || scheme.equals("http") || apiUri.getHost() == null) {
|
||||||
|
Utils.showToastLong("Invalid DeArrow API URL. Using default");
|
||||||
|
Settings.ALT_THUMBNAIL_DEARROW_API_URL.resetToDefault();
|
||||||
|
return validateSettings();
|
||||||
|
}
|
||||||
|
return apiUri;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ThumbnailOption optionSettingForCurrentNavigation() {
|
||||||
|
// Must check player type first, as search bar can be active behind the player.
|
||||||
|
if (PlayerType.getCurrent().isMaximizedOrFullscreen()) {
|
||||||
|
return ALT_THUMBNAIL_PLAYER.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Must check second, as search can be from any tab.
|
||||||
|
if (NavigationBar.isSearchBarActive()) {
|
||||||
|
return ALT_THUMBNAIL_SEARCH.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Avoid checking which navigation button is selected, if all other settings are the same.
|
||||||
|
ThumbnailOption homeOption = ALT_THUMBNAIL_HOME.get();
|
||||||
|
ThumbnailOption subscriptionsOption = ALT_THUMBNAIL_SUBSCRIPTIONS.get();
|
||||||
|
ThumbnailOption libraryOption = ALT_THUMBNAIL_LIBRARY.get();
|
||||||
|
if ((homeOption == subscriptionsOption) && (homeOption == libraryOption)) {
|
||||||
|
return homeOption; // All are the same option.
|
||||||
|
}
|
||||||
|
|
||||||
|
NavigationButton selectedNavButton = NavigationButton.getSelectedNavigationButton();
|
||||||
|
if (selectedNavButton == null) {
|
||||||
|
// Unknown tab, treat as the home tab;
|
||||||
|
return homeOption;
|
||||||
|
}
|
||||||
|
if (selectedNavButton == NavigationButton.HOME) {
|
||||||
|
return homeOption;
|
||||||
|
}
|
||||||
|
if (selectedNavButton == NavigationButton.SUBSCRIPTIONS || selectedNavButton == NavigationButton.NOTIFICATIONS) {
|
||||||
|
return subscriptionsOption;
|
||||||
|
}
|
||||||
|
// A library tab variant is active.
|
||||||
|
return libraryOption;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the alternative thumbnail url using YouTube provided still video captures.
|
||||||
|
*
|
||||||
|
* @param decodedUrl Decoded original thumbnail request url.
|
||||||
|
* @return The alternative thumbnail url, or if not available NULL.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private static String buildYouTubeVideoStillURL(@NonNull DecodedThumbnailUrl decodedUrl,
|
||||||
|
@NonNull ThumbnailQuality qualityToUse) {
|
||||||
|
String sanitizedReplacement = decodedUrl.createStillsUrl(qualityToUse, false);
|
||||||
|
if (VerifiedQualities.verifyAltThumbnailExist(decodedUrl.videoId, qualityToUse, sanitizedReplacement)) {
|
||||||
|
return sanitizedReplacement;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the alternative thumbnail url using DeArrow thumbnail cache.
|
||||||
|
*
|
||||||
|
* @param videoId ID of the video to get a thumbnail of. Can be any video (regular or Short).
|
||||||
|
* @param fallbackUrl URL to fall back to in case.
|
||||||
|
* @return The alternative thumbnail url, without tracking parameters.
|
||||||
|
*/
|
||||||
|
@NonNull
|
||||||
|
private static String buildDeArrowThumbnailURL(String videoId, String fallbackUrl) {
|
||||||
|
// Build thumbnail request url.
|
||||||
|
// See https://github.com/ajayyy/DeArrowThumbnailCache/blob/29eb4359ebdf823626c79d944a901492d760bbbc/app.py#L29.
|
||||||
|
return dearrowApiUri
|
||||||
|
.buildUpon()
|
||||||
|
.appendQueryParameter("videoID", videoId)
|
||||||
|
.appendQueryParameter("redirectUrl", fallbackUrl)
|
||||||
|
.build()
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean urlIsDeArrow(@NonNull String imageUrl) {
|
||||||
|
return imageUrl.startsWith(deArrowApiUrlPrefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return If this client has not recently experienced any DeArrow API errors.
|
||||||
|
*/
|
||||||
|
private static boolean canUseDeArrowAPI() {
|
||||||
|
if (timeToResumeDeArrowAPICalls == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (timeToResumeDeArrowAPICalls < System.currentTimeMillis()) {
|
||||||
|
Logger.printDebug(() -> "Resuming DeArrow API calls");
|
||||||
|
timeToResumeDeArrowAPICalls = 0;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void handleDeArrowError(@NonNull String url, int statusCode) {
|
||||||
|
Logger.printDebug(() -> "Encountered DeArrow error. Url: " + url);
|
||||||
|
final long now = System.currentTimeMillis();
|
||||||
|
if (timeToResumeDeArrowAPICalls < now) {
|
||||||
|
timeToResumeDeArrowAPICalls = now + DEARROW_FAILURE_API_BACKOFF_MILLISECONDS;
|
||||||
|
if (Settings.ALT_THUMBNAIL_DEARROW_CONNECTION_TOAST.get()) {
|
||||||
|
String toastMessage = (statusCode != 0)
|
||||||
|
? str("revanced_alt_thumbnail_dearrow_error", statusCode)
|
||||||
|
: str("revanced_alt_thumbnail_dearrow_error_generic");
|
||||||
|
Utils.showToastLong(toastMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injection point. Called off the main thread and by multiple threads at the same time.
|
||||||
|
*
|
||||||
|
* @param originalUrl Image url for all url images loaded, including video thumbnails.
|
||||||
|
*/
|
||||||
|
public static String overrideImageURL(String originalUrl) {
|
||||||
|
try {
|
||||||
|
ThumbnailOption option = optionSettingForCurrentNavigation();
|
||||||
|
|
||||||
|
if (option == ThumbnailOption.ORIGINAL) {
|
||||||
|
return originalUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
final var decodedUrl = DecodedThumbnailUrl.decodeImageUrl(originalUrl);
|
||||||
|
if (decodedUrl == null) {
|
||||||
|
return originalUrl; // Not a thumbnail.
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.printDebug(() -> "Original url: " + decodedUrl.sanitizedUrl);
|
||||||
|
|
||||||
|
ThumbnailQuality qualityToUse = ThumbnailQuality.getQualityToUse(decodedUrl.imageQuality);
|
||||||
|
if (qualityToUse == null) {
|
||||||
|
// Thumbnail is a Short or a Storyboard image used for seekbar thumbnails (must not replace these).
|
||||||
|
return originalUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
String sanitizedReplacementUrl;
|
||||||
|
final boolean includeTracking;
|
||||||
|
if (option.useDeArrow && canUseDeArrowAPI()) {
|
||||||
|
includeTracking = false; // Do not include view tracking parameters with API call.
|
||||||
|
String fallbackUrl = null;
|
||||||
|
if (option.useStillImages) {
|
||||||
|
fallbackUrl = buildYouTubeVideoStillURL(decodedUrl, qualityToUse);
|
||||||
|
}
|
||||||
|
if (fallbackUrl == null) {
|
||||||
|
fallbackUrl = decodedUrl.sanitizedUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
sanitizedReplacementUrl = buildDeArrowThumbnailURL(decodedUrl.videoId, fallbackUrl);
|
||||||
|
} else if (option.useStillImages) {
|
||||||
|
includeTracking = true; // Include view tracking parameters if present.
|
||||||
|
sanitizedReplacementUrl = buildYouTubeVideoStillURL(decodedUrl, qualityToUse);
|
||||||
|
if (sanitizedReplacementUrl == null) {
|
||||||
|
return originalUrl; // Still capture is not available. Return the untouched original url.
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return originalUrl; // Recently experienced DeArrow failure and video stills are not enabled.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not log any tracking parameters.
|
||||||
|
Logger.printDebug(() -> "Replacement url: " + sanitizedReplacementUrl);
|
||||||
|
|
||||||
|
return includeTracking
|
||||||
|
? sanitizedReplacementUrl + decodedUrl.viewTrackingParameters
|
||||||
|
: sanitizedReplacementUrl;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "overrideImageURL failure", ex);
|
||||||
|
return originalUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injection point.
|
||||||
|
* <p>
|
||||||
|
* Cronet considers all completed connections as a success, even if the response is 404 or 5xx.
|
||||||
|
*/
|
||||||
|
public static void handleCronetSuccess(UrlRequest request, @NonNull UrlResponseInfo responseInfo) {
|
||||||
|
try {
|
||||||
|
final int statusCode = responseInfo.getHttpStatusCode();
|
||||||
|
if (statusCode == 200) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String url = responseInfo.getUrl();
|
||||||
|
|
||||||
|
if (urlIsDeArrow(url)) {
|
||||||
|
Logger.printDebug(() -> "handleCronetSuccess, statusCode: " + statusCode);
|
||||||
|
if (statusCode == 304) {
|
||||||
|
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304
|
||||||
|
return; // Normal response.
|
||||||
|
}
|
||||||
|
handleDeArrowError(url, statusCode);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statusCode == 404) {
|
||||||
|
// Fast alt thumbnails is enabled and the thumbnail is not available.
|
||||||
|
// The video is:
|
||||||
|
// - live stream
|
||||||
|
// - upcoming unreleased video
|
||||||
|
// - very old
|
||||||
|
// - very low view count
|
||||||
|
// Take note of this, so if the image reloads the original thumbnail will be used.
|
||||||
|
DecodedThumbnailUrl decodedUrl = DecodedThumbnailUrl.decodeImageUrl(url);
|
||||||
|
if (decodedUrl == null) {
|
||||||
|
return; // Not a thumbnail.
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.printDebug(() -> "handleCronetSuccess, image not available: " + decodedUrl.sanitizedUrl);
|
||||||
|
|
||||||
|
ThumbnailQuality quality = ThumbnailQuality.altImageNameToQuality(decodedUrl.imageQuality);
|
||||||
|
if (quality == null) {
|
||||||
|
// Video is a short or a seekbar thumbnail, but somehow did not load. Should not happen.
|
||||||
|
Logger.printDebug(() -> "Failed to recognize image quality of url: " + decodedUrl.sanitizedUrl);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
VerifiedQualities.setAltThumbnailDoesNotExist(decodedUrl.videoId, quality);
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "Callback success error", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injection point.
|
||||||
|
* <p>
|
||||||
|
* To test failure cases, try changing the API URL to each of:
|
||||||
|
* - A non-existent domain.
|
||||||
|
* - A url path of something incorrect (ie: /v1/nonExistentEndPoint).
|
||||||
|
* <p>
|
||||||
|
* Cronet uses a very timeout (several minutes), so if the API never responds this hook can take a while to be called.
|
||||||
|
* But this does not appear to be a problem, as the DeArrow API has not been observed to 'go silent'
|
||||||
|
* Instead if there's a problem it returns an error code status response, which is handled in this patch.
|
||||||
|
*/
|
||||||
|
public static void handleCronetFailure(UrlRequest request,
|
||||||
|
@Nullable UrlResponseInfo responseInfo,
|
||||||
|
IOException exception) {
|
||||||
|
try {
|
||||||
|
String url = ((CronetUrlRequest) request).getHookedUrl();
|
||||||
|
if (urlIsDeArrow(url)) {
|
||||||
|
Logger.printDebug(() -> "handleCronetFailure, exception: " + exception);
|
||||||
|
final int statusCode = (responseInfo != null)
|
||||||
|
? responseInfo.getHttpStatusCode()
|
||||||
|
: 0;
|
||||||
|
handleDeArrowError(url, statusCode);
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
Logger.printException(() -> "Callback failure error", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum ThumbnailQuality {
|
||||||
|
// In order of lowest to highest resolution.
|
||||||
|
DEFAULT("default", ""), // effective alt name is 1.jpg, 2.jpg, 3.jpg
|
||||||
|
MQDEFAULT("mqdefault", "mq"),
|
||||||
|
HQDEFAULT("hqdefault", "hq"),
|
||||||
|
SDDEFAULT("sddefault", "sd"),
|
||||||
|
HQ720("hq720", "hq720_"),
|
||||||
|
MAXRESDEFAULT("maxresdefault", "maxres");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lookup map of original name to enum.
|
||||||
|
*/
|
||||||
|
private static final Map<String, ThumbnailQuality> originalNameToEnum = new HashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lookup map of alt name to enum. ie: "hq720_1" to {@link #HQ720}.
|
||||||
|
*/
|
||||||
|
private static final Map<String, ThumbnailQuality> altNameToEnum = new HashMap<>();
|
||||||
|
|
||||||
|
static {
|
||||||
|
for (ThumbnailQuality quality : values()) {
|
||||||
|
originalNameToEnum.put(quality.originalName, quality);
|
||||||
|
|
||||||
|
for (ThumbnailStillTime time : ThumbnailStillTime.values()) {
|
||||||
|
// 'custom' thumbnails set by the content creator.
|
||||||
|
// These show up in place of regular thumbnails
|
||||||
|
// and seem to be limited to the same [1, 3] range as the still captures.
|
||||||
|
originalNameToEnum.put(quality.originalName + "_custom_" + time.altImageNumber, quality);
|
||||||
|
|
||||||
|
altNameToEnum.put(quality.altImageName + time.altImageNumber, quality);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert an alt image name to enum.
|
||||||
|
* ie: "hq720_2" returns {@link #HQ720}.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
static ThumbnailQuality altImageNameToQuality(@NonNull String altImageName) {
|
||||||
|
return altNameToEnum.get(altImageName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Original quality to effective alt quality to use.
|
||||||
|
* ie: If fast alt image is enabled, then "hq720" returns {@link #SDDEFAULT}.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
static ThumbnailQuality getQualityToUse(@NonNull String originalSize) {
|
||||||
|
ThumbnailQuality quality = originalNameToEnum.get(originalSize);
|
||||||
|
if (quality == null) {
|
||||||
|
return null; // Not a thumbnail for a regular video.
|
||||||
|
}
|
||||||
|
|
||||||
|
final boolean useFastQuality = Settings.ALT_THUMBNAIL_STILLS_FAST.get();
|
||||||
|
switch (quality) {
|
||||||
|
case SDDEFAULT:
|
||||||
|
// SD alt images have somewhat worse quality with washed out color and poor contrast.
|
||||||
|
// But the 720 images look much better and don't suffer from these issues.
|
||||||
|
// For unknown reasons, the 720 thumbnails are used only for the home feed,
|
||||||
|
// while SD is used for the search and subscription feed
|
||||||
|
// (even though search and subscriptions use the exact same layout as the home feed).
|
||||||
|
// Of note, this image quality issue only appears with the alt thumbnail images,
|
||||||
|
// and the regular thumbnails have identical color/contrast quality for all sizes.
|
||||||
|
// Fix this by falling thru and upgrading SD to 720.
|
||||||
|
case HQ720:
|
||||||
|
if (useFastQuality) {
|
||||||
|
return SDDEFAULT; // SD is max resolution for fast alt images.
|
||||||
|
}
|
||||||
|
return HQ720;
|
||||||
|
case MAXRESDEFAULT:
|
||||||
|
if (useFastQuality) {
|
||||||
|
return SDDEFAULT;
|
||||||
|
}
|
||||||
|
return MAXRESDEFAULT;
|
||||||
|
default:
|
||||||
|
return quality;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final String originalName;
|
||||||
|
final String altImageName;
|
||||||
|
|
||||||
|
ThumbnailQuality(String originalName, String altImageName) {
|
||||||
|
this.originalName = originalName;
|
||||||
|
this.altImageName = altImageName;
|
||||||
|
}
|
||||||
|
|
||||||
|
String getAltImageNameToUse() {
|
||||||
|
return altImageName + Settings.ALT_THUMBNAIL_STILLS_TIME.get().altImageNumber;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uses HTTP HEAD requests to verify and keep track of which thumbnail sizes
|
||||||
|
* are available and not available.
|
||||||
|
*/
|
||||||
|
private static class VerifiedQualities {
|
||||||
|
/**
|
||||||
|
* After a quality is verified as not available, how long until the quality is re-verified again.
|
||||||
|
* Used only if fast mode is not enabled. Intended for live streams and unreleased videos
|
||||||
|
* that are now finished and available (and thus, the alt thumbnails are also now available).
|
||||||
|
*/
|
||||||
|
private static final long NOT_AVAILABLE_TIMEOUT_MILLISECONDS = 10 * 60 * 1000; // 10 minutes.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache used to verify if an alternative thumbnails exists for a given video id.
|
||||||
|
*/
|
||||||
|
@GuardedBy("itself")
|
||||||
|
private static final Map<String, VerifiedQualities> altVideoIdLookup = new LinkedHashMap<>(100) {
|
||||||
|
private static final int CACHE_LIMIT = 1000;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected boolean removeEldestEntry(Entry eldest) {
|
||||||
|
return size() > CACHE_LIMIT; // Evict the oldest entry if over the cache limit.
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
private static VerifiedQualities getVerifiedQualities(@NonNull String videoId, boolean returnNullIfDoesNotExist) {
|
||||||
|
synchronized (altVideoIdLookup) {
|
||||||
|
VerifiedQualities verified = altVideoIdLookup.get(videoId);
|
||||||
|
if (verified == null) {
|
||||||
|
if (returnNullIfDoesNotExist) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
verified = new VerifiedQualities();
|
||||||
|
altVideoIdLookup.put(videoId, verified);
|
||||||
|
}
|
||||||
|
return verified;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean verifyAltThumbnailExist(@NonNull String videoId, @NonNull ThumbnailQuality quality,
|
||||||
|
@NonNull String imageUrl) {
|
||||||
|
VerifiedQualities verified = getVerifiedQualities(videoId, Settings.ALT_THUMBNAIL_STILLS_FAST.get());
|
||||||
|
if (verified == null) return true; // Fast alt thumbnails is enabled.
|
||||||
|
return verified.verifyYouTubeThumbnailExists(videoId, quality, imageUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void setAltThumbnailDoesNotExist(@NonNull String videoId, @NonNull ThumbnailQuality quality) {
|
||||||
|
VerifiedQualities verified = getVerifiedQualities(videoId, false);
|
||||||
|
//noinspection ConstantConditions
|
||||||
|
verified.setQualityVerified(videoId, quality, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Highest quality verified as existing.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private ThumbnailQuality highestQualityVerified;
|
||||||
|
/**
|
||||||
|
* Lowest quality verified as not existing.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private ThumbnailQuality lowestQualityNotAvailable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* System time, of when to invalidate {@link #lowestQualityNotAvailable}.
|
||||||
|
* Used only if fast mode is not enabled.
|
||||||
|
*/
|
||||||
|
private long timeToReVerifyLowestQuality;
|
||||||
|
|
||||||
|
private synchronized void setQualityVerified(String videoId, ThumbnailQuality quality, boolean isVerified) {
|
||||||
|
if (isVerified) {
|
||||||
|
if (highestQualityVerified == null || highestQualityVerified.ordinal() < quality.ordinal()) {
|
||||||
|
highestQualityVerified = quality;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (lowestQualityNotAvailable == null || lowestQualityNotAvailable.ordinal() > quality.ordinal()) {
|
||||||
|
lowestQualityNotAvailable = quality;
|
||||||
|
timeToReVerifyLowestQuality = System.currentTimeMillis() + NOT_AVAILABLE_TIMEOUT_MILLISECONDS;
|
||||||
|
}
|
||||||
|
Logger.printDebug(() -> quality + " not available for video: " + videoId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify if a video alt thumbnail exists. Does so by making a minimal HEAD http request.
|
||||||
|
*/
|
||||||
|
synchronized boolean verifyYouTubeThumbnailExists(@NonNull String videoId, @NonNull ThumbnailQuality quality,
|
||||||
|
@NonNull String imageUrl) {
|
||||||
|
if (highestQualityVerified != null && highestQualityVerified.ordinal() >= quality.ordinal()) {
|
||||||
|
return true; // Previously verified as existing.
|
||||||
|
}
|
||||||
|
|
||||||
|
final boolean fastQuality = Settings.ALT_THUMBNAIL_STILLS_FAST.get();
|
||||||
|
if (lowestQualityNotAvailable != null && lowestQualityNotAvailable.ordinal() <= quality.ordinal()) {
|
||||||
|
if (fastQuality || System.currentTimeMillis() < timeToReVerifyLowestQuality) {
|
||||||
|
return false; // Previously verified as not existing.
|
||||||
|
}
|
||||||
|
// Enough time has passed, and should re-verify again.
|
||||||
|
Logger.printDebug(() -> "Resetting lowest verified quality for: " + videoId);
|
||||||
|
lowestQualityNotAvailable = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fastQuality) {
|
||||||
|
return true; // Unknown if it exists or not. Use the URL anyways and update afterwards if loading fails.
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean imageFileFound;
|
||||||
|
try {
|
||||||
|
// This hooked code is running on a low priority thread, and it's slightly faster
|
||||||
|
// to run the url connection through the extension thread pool which runs at the highest priority.
|
||||||
|
final long start = System.currentTimeMillis();
|
||||||
|
imageFileFound = Utils.submitOnBackgroundThread(() -> {
|
||||||
|
final int connectionTimeoutMillis = 10000; // 10 seconds.
|
||||||
|
HttpURLConnection connection = (HttpURLConnection) new URL(imageUrl).openConnection();
|
||||||
|
connection.setConnectTimeout(connectionTimeoutMillis);
|
||||||
|
connection.setReadTimeout(connectionTimeoutMillis);
|
||||||
|
connection.setRequestMethod("HEAD");
|
||||||
|
// Even with a HEAD request, the response is the same size as a full GET request.
|
||||||
|
// Using an empty range fixes this.
|
||||||
|
connection.setRequestProperty("Range", "bytes=0-0");
|
||||||
|
final int responseCode = connection.getResponseCode();
|
||||||
|
if (responseCode == HttpURLConnection.HTTP_PARTIAL) {
|
||||||
|
String contentType = connection.getContentType();
|
||||||
|
return (contentType != null && contentType.startsWith("image"));
|
||||||
|
}
|
||||||
|
if (responseCode != HttpURLConnection.HTTP_NOT_FOUND) {
|
||||||
|
Logger.printDebug(() -> "Unexpected response code: " + responseCode + " for url: " + imageUrl);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}).get();
|
||||||
|
Logger.printDebug(() -> "Verification took: " + (System.currentTimeMillis() - start) + "ms for image: " + imageUrl);
|
||||||
|
} catch (ExecutionException | InterruptedException ex) {
|
||||||
|
Logger.printInfo(() -> "Could not verify alt url: " + imageUrl, ex);
|
||||||
|
imageFileFound = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
setQualityVerified(videoId, quality, imageFileFound);
|
||||||
|
return imageFileFound;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* YouTube video thumbnail url, decoded into it's relevant parts.
|
||||||
|
*/
|
||||||
|
private static class DecodedThumbnailUrl {
|
||||||
|
private static final String YOUTUBE_THUMBNAIL_DOMAIN = "https://i.ytimg.com/";
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
static DecodedThumbnailUrl decodeImageUrl(String url) {
|
||||||
|
final int urlPathStartIndex = url.indexOf('/', "https://".length()) + 1;
|
||||||
|
if (urlPathStartIndex <= 0) return null;
|
||||||
|
|
||||||
|
final int urlPathEndIndex = url.indexOf('/', urlPathStartIndex);
|
||||||
|
if (urlPathEndIndex < 0) return null;
|
||||||
|
|
||||||
|
final int videoIdStartIndex = url.indexOf('/', urlPathEndIndex) + 1;
|
||||||
|
if (videoIdStartIndex <= 0) return null;
|
||||||
|
|
||||||
|
final int videoIdEndIndex = url.indexOf('/', videoIdStartIndex);
|
||||||
|
if (videoIdEndIndex < 0) return null;
|
||||||
|
|
||||||
|
final int imageSizeStartIndex = videoIdEndIndex + 1;
|
||||||
|
final int imageSizeEndIndex = url.indexOf('.', imageSizeStartIndex);
|
||||||
|
if (imageSizeEndIndex < 0) return null;
|
||||||
|
|
||||||
|
int imageExtensionEndIndex = url.indexOf('?', imageSizeEndIndex);
|
||||||
|
if (imageExtensionEndIndex < 0) imageExtensionEndIndex = url.length();
|
||||||
|
|
||||||
|
return new DecodedThumbnailUrl(url, urlPathStartIndex, urlPathEndIndex, videoIdStartIndex, videoIdEndIndex,
|
||||||
|
imageSizeStartIndex, imageSizeEndIndex, imageExtensionEndIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
final String originalFullUrl;
|
||||||
|
/** Full usable url, but stripped of any tracking information. */
|
||||||
|
final String sanitizedUrl;
|
||||||
|
/** Url path, such as 'vi' or 'vi_webp' */
|
||||||
|
final String urlPath;
|
||||||
|
final String videoId;
|
||||||
|
/** Quality, such as hq720 or sddefault. */
|
||||||
|
final String imageQuality;
|
||||||
|
/** JPG or WEBP */
|
||||||
|
final String imageExtension;
|
||||||
|
/** User view tracking parameters, only present on some images. */
|
||||||
|
final String viewTrackingParameters;
|
||||||
|
|
||||||
|
DecodedThumbnailUrl(String fullUrl, int urlPathStartIndex, int urlPathEndIndex, int videoIdStartIndex, int videoIdEndIndex,
|
||||||
|
int imageSizeStartIndex, int imageSizeEndIndex, int imageExtensionEndIndex) {
|
||||||
|
originalFullUrl = fullUrl;
|
||||||
|
sanitizedUrl = fullUrl.substring(0, imageExtensionEndIndex);
|
||||||
|
urlPath = fullUrl.substring(urlPathStartIndex, urlPathEndIndex);
|
||||||
|
videoId = fullUrl.substring(videoIdStartIndex, videoIdEndIndex);
|
||||||
|
imageQuality = fullUrl.substring(imageSizeStartIndex, imageSizeEndIndex);
|
||||||
|
imageExtension = fullUrl.substring(imageSizeEndIndex + 1, imageExtensionEndIndex);
|
||||||
|
viewTrackingParameters = (imageExtensionEndIndex == fullUrl.length())
|
||||||
|
? "" : fullUrl.substring(imageExtensionEndIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @noinspection SameParameterValue */
|
||||||
|
String createStillsUrl(@NonNull ThumbnailQuality qualityToUse, boolean includeViewTracking) {
|
||||||
|
// Images could be upgraded to webp if they are not already, but this fails quite often,
|
||||||
|
// especially for new videos uploaded in the last hour.
|
||||||
|
// And even if alt webp images do exist, sometimes they can load much slower than the original jpg alt images.
|
||||||
|
// (as much as 4x slower network response has been observed, despite the alt webp image being a smaller file).
|
||||||
|
StringBuilder builder = new StringBuilder(originalFullUrl.length() + 2);
|
||||||
|
// Many different "i.ytimage.com" domains exist such as "i9.ytimg.com",
|
||||||
|
// but still captures are frequently not available on the other domains (especially newly uploaded videos).
|
||||||
|
// So always use the primary domain for a higher success rate.
|
||||||
|
builder.append(YOUTUBE_THUMBNAIL_DOMAIN).append(urlPath).append('/');
|
||||||
|
builder.append(videoId).append('/');
|
||||||
|
builder.append(qualityToUse.getAltImageNameToUse());
|
||||||
|
builder.append('.').append(imageExtension);
|
||||||
|
if (includeViewTracking) {
|
||||||
|
builder.append(viewTrackingParameters);
|
||||||
|
}
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
package app.revanced.extension.youtube.patches;
|
||||||
|
|
||||||
|
import app.revanced.extension.youtube.settings.Settings;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class AutoRepeatPatch {
|
||||||
|
//Used by app.revanced.patches.youtube.layout.autorepeat.patch.AutoRepeatPatch
|
||||||
|
public static boolean shouldAutoRepeat() {
|
||||||
|
return Settings.AUTO_REPEAT.get();
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user