file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
FullscreenPanelsRemoverPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/FullscreenPanelsRemoverPatch.java
package app.revanced.integrations.youtube.patches; import android.view.View; import app.revanced.integrations.youtube.settings.Settings; @SuppressWarnings("unused") public class FullscreenPanelsRemoverPatch { public static int getFullscreenPanelsVisibility() { return Settings.HIDE_FULLSCREEN_PANELS.get() ? View.GONE : View.VISIBLE; } }
357
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
HideGetPremiumPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideGetPremiumPatch.java
package app.revanced.integrations.youtube.patches; import app.revanced.integrations.youtube.settings.Settings; @SuppressWarnings("unused") public class HideGetPremiumPatch { /** * Injection point. */ public static boolean hideGetPremiumView() { return Settings.HIDE_GET_PREMIUM.get(); } }
321
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ChangeStartPagePatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/ChangeStartPagePatch.java
package app.revanced.integrations.youtube.patches; import android.content.Intent; import android.net.Uri; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.youtube.settings.Settings; @SuppressWarnings("unused") public final class ChangeStartPagePatch { public static void changeIntent(final Intent intent) { final var startPage = Settings.START_PAGE.get(); if (startPage.isEmpty()) return; Logger.printDebug(() -> "Changing start page to " + startPage); if (startPage.startsWith("www")) intent.setData(Uri.parse(startPage)); else intent.setAction("com.google.android.youtube.action." + startPage); } }
709
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
HidePlayerButtonsPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HidePlayerButtonsPatch.java
package app.revanced.integrations.youtube.patches; import app.revanced.integrations.youtube.settings.Settings; @SuppressWarnings("unused") public final class HidePlayerButtonsPatch { /** * Injection point. */ public static boolean previousOrNextButtonIsVisible(boolean previousOrNextButtonVisible) { if (Settings.HIDE_PLAYER_BUTTONS.get()) { return false; } return previousOrNextButtonVisible; } }
459
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
HideFilterBarPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/HideFilterBarPatch.java
package app.revanced.integrations.youtube.patches; import android.view.View; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.shared.Utils; @SuppressWarnings("unused") public final class HideFilterBarPatch { public static int hideInFeed(final int height) { if (Settings.HIDE_FILTER_BAR_FEED_IN_FEED.get()) return 0; return height; } public static void hideInRelatedVideos(final View chipView) { if (!Settings.HIDE_FILTER_BAR_FEED_IN_RELATED_VIDEOS.get()) return; Utils.hideViewByLayoutParams(chipView); } public static int hideInSearch(final int height) { if (Settings.HIDE_FILTER_BAR_FEED_IN_SEARCH.get()) return 0; return height; } }
760
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
CustomPlaybackSpeedPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/playback/speed/CustomPlaybackSpeedPatch.java
package app.revanced.integrations.youtube.patches.playback.speed; import static app.revanced.integrations.shared.StringRef.str; import android.preference.ListPreference; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import app.revanced.integrations.youtube.patches.components.PlaybackSpeedMenuFilterPatch; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import java.util.Arrays; @SuppressWarnings("unused") public class CustomPlaybackSpeedPatch { /** * Maximum playback speed, exclusive value. Custom speeds must be less than this value. * * Going over 8x does not increase the actual playback speed any higher, * and the UI selector starts flickering and acting weird. * Over 10x and the speeds show up out of order in the UI selector. */ public static final float MAXIMUM_PLAYBACK_SPEED = 8; /** * Custom playback speeds. */ public static float[] customPlaybackSpeeds; /** * The last time the old playback menu was forcefully called. */ private static long lastTimeOldPlaybackMenuInvoked; /** * PreferenceList entries and values, of all available playback speeds. */ private static String[] preferenceListEntries, preferenceListEntryValues; static { loadCustomSpeeds(); } private static void resetCustomSpeeds(@NonNull String toastMessage) { Utils.showToastLong(toastMessage); Settings.CUSTOM_PLAYBACK_SPEEDS.resetToDefault(); } private static void loadCustomSpeeds() { try { String[] speedStrings = Settings.CUSTOM_PLAYBACK_SPEEDS.get().split("\\s+"); Arrays.sort(speedStrings); if (speedStrings.length == 0) { throw new IllegalArgumentException(); } customPlaybackSpeeds = new float[speedStrings.length]; for (int i = 0, length = speedStrings.length; i < length; i++) { final float speed = Float.parseFloat(speedStrings[i]); if (speed <= 0 || arrayContains(customPlaybackSpeeds, speed)) { throw new IllegalArgumentException(); } if (speed >= MAXIMUM_PLAYBACK_SPEED) { resetCustomSpeeds(str("revanced_custom_playback_speeds_invalid", MAXIMUM_PLAYBACK_SPEED)); loadCustomSpeeds(); return; } customPlaybackSpeeds[i] = speed; } } catch (Exception ex) { Logger.printInfo(() -> "parse error", ex); resetCustomSpeeds(str("revanced_custom_playback_speeds_parse_exception")); loadCustomSpeeds(); } } private static boolean arrayContains(float[] array, float value) { for (float arrayValue : array) { if (arrayValue == value) return true; } return false; } /** * Initialize a settings preference list with the available playback speeds. */ public static void initializeListPreference(ListPreference preference) { if (preferenceListEntries == null) { preferenceListEntries = new String[customPlaybackSpeeds.length]; preferenceListEntryValues = new String[customPlaybackSpeeds.length]; int i = 0; for (float speed : customPlaybackSpeeds) { String speedString = String.valueOf(speed); preferenceListEntries[i] = speedString + "x"; preferenceListEntryValues[i] = speedString; i++; } } preference.setEntries(preferenceListEntries); preference.setEntryValues(preferenceListEntryValues); } /** * Injection point. */ public static void onFlyoutMenuCreate(RecyclerView recyclerView) { recyclerView.getViewTreeObserver().addOnDrawListener(() -> { try { // For some reason, the custom playback speed flyout panel is activated when the user opens the share panel. (A/B tests) // Check the child count of playback speed flyout panel to prevent this issue. // Child count of playback speed flyout panel is always 8. if (!PlaybackSpeedMenuFilterPatch.isPlaybackSpeedMenuVisible || recyclerView.getChildCount() == 0) { return; } ViewGroup PlaybackSpeedParentView = (ViewGroup) recyclerView.getChildAt(0); if (PlaybackSpeedParentView == null || PlaybackSpeedParentView.getChildCount() != 8) { return; } PlaybackSpeedMenuFilterPatch.isPlaybackSpeedMenuVisible = false; ViewGroup parentView3rd = (ViewGroup) recyclerView.getParent().getParent().getParent(); ViewGroup parentView4th = (ViewGroup) parentView3rd.getParent(); // Dismiss View [R.id.touch_outside] is the 1st ChildView of the 4th ParentView. // This only shows in phone layout. final var touchInsidedView = parentView4th.getChildAt(0); touchInsidedView.setSoundEffectsEnabled(false); touchInsidedView.performClick(); // In tablet layout there is no Dismiss View, instead we just hide all two parent views. parentView3rd.setVisibility(View.GONE); parentView4th.setVisibility(View.GONE); // This works without issues for both tablet and phone layouts, // So no code is needed to check whether the current device is a tablet or phone. // Close the new Playback speed menu and show the old one. showOldPlaybackSpeedMenu(); } catch (Exception ex) { Logger.printException(() -> "onFlyoutMenuCreate failure", ex); } }); } private static void showOldPlaybackSpeedMenu() { // This method is sometimes used multiple times. // To prevent this, ignore method reuse within 1 second. final long now = System.currentTimeMillis(); if (now - lastTimeOldPlaybackMenuInvoked < 1000) { Logger.printDebug(() -> "Ignoring call to showOldPlaybackSpeedMenu"); return; } lastTimeOldPlaybackMenuInvoked = now; Logger.printDebug(() -> "Old video quality menu shown"); // Rest of the implementation added by patch. } }
6,643
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
RememberPlaybackSpeedPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/playback/speed/RememberPlaybackSpeedPatch.java
package app.revanced.integrations.youtube.patches.playback.speed; import static app.revanced.integrations.shared.StringRef.str; import app.revanced.integrations.youtube.patches.VideoInformation; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; @SuppressWarnings("unused") public final class RememberPlaybackSpeedPatch { /** * Injection point. */ public static void newVideoStarted(Object ignoredPlayerController) { Logger.printDebug(() -> "newVideoStarted"); VideoInformation.overridePlaybackSpeed(Settings.PLAYBACK_SPEED_DEFAULT.get()); } /** * Injection point. * Called when user selects a playback speed. * * @param playbackSpeed The playback speed the user selected */ public static void userSelectedPlaybackSpeed(float playbackSpeed) { if (Settings.REMEMBER_PLAYBACK_SPEED_LAST_SELECTED.get()) { Settings.PLAYBACK_SPEED_DEFAULT.save(playbackSpeed); Utils.showToastLong(str("revanced_remember_playback_speed_toast", (playbackSpeed + "x"))); } } /** * Injection point. * Overrides the video speed. Called after video loads, and immediately after user selects a different playback speed */ public static float getPlaybackSpeedOverride() { return VideoInformation.getPlaybackSpeed(); } }
1,453
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
RememberVideoQualityPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/playback/quality/RememberVideoQualityPatch.java
package app.revanced.integrations.youtube.patches.playback.quality; import androidx.annotation.Nullable; import app.revanced.integrations.shared.settings.IntegerSetting; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import static app.revanced.integrations.shared.StringRef.str; import static app.revanced.integrations.shared.Utils.NetworkType; @SuppressWarnings("unused") public class RememberVideoQualityPatch { private static final int AUTOMATIC_VIDEO_QUALITY_VALUE = -2; private static final IntegerSetting wifiQualitySetting = Settings.VIDEO_QUALITY_DEFAULT_WIFI; private static final IntegerSetting mobileQualitySetting = Settings.VIDEO_QUALITY_DEFAULT_MOBILE; private static boolean qualityNeedsUpdating; /** * If the user selected a new quality from the flyout menu, * and {@link Settings#REMEMBER_VIDEO_QUALITY_LAST_SELECTED} is enabled. */ private static boolean userChangedDefaultQuality; /** * Index of the video quality chosen by the user from the flyout menu. */ private static int userSelectedQualityIndex; /** * The available qualities of the current video in human readable form: [1080, 720, 480] */ @Nullable private static List<Integer> videoQualities; private static void changeDefaultQuality(int defaultQuality) { String networkTypeMessage; if (Utils.getNetworkType() == NetworkType.MOBILE) { mobileQualitySetting.save(defaultQuality); networkTypeMessage = str("revanced_remember_video_quality_mobile"); } else { wifiQualitySetting.save(defaultQuality); networkTypeMessage = str("revanced_remember_video_quality_wifi"); } Utils.showToastShort( str("revanced_remember_video_quality_toast", networkTypeMessage, (defaultQuality + "p"))); } /** * Injection point. * * @param qualities Video qualities available, ordered from largest to smallest, with index 0 being the 'automatic' value of -2 * @param originalQualityIndex quality index to use, as chosen by YouTube */ public static int setVideoQuality(Object[] qualities, final int originalQualityIndex, Object qInterface, String qIndexMethod) { try { if (!(qualityNeedsUpdating || userChangedDefaultQuality) || qInterface == null) { return originalQualityIndex; } qualityNeedsUpdating = false; final int preferredQuality; if (Utils.getNetworkType() == NetworkType.MOBILE) { preferredQuality = mobileQualitySetting.get(); } else { preferredQuality = wifiQualitySetting.get(); } if (!userChangedDefaultQuality && preferredQuality == AUTOMATIC_VIDEO_QUALITY_VALUE) { return originalQualityIndex; // nothing to do } if (videoQualities == null || videoQualities.size() != qualities.length) { videoQualities = new ArrayList<>(qualities.length); for (Object streamQuality : qualities) { for (Field field : streamQuality.getClass().getFields()) { if (field.getType().isAssignableFrom(Integer.TYPE) && field.getName().length() <= 2) { videoQualities.add(field.getInt(streamQuality)); } } } Logger.printDebug(() -> "videoQualities: " + videoQualities); } if (userChangedDefaultQuality) { userChangedDefaultQuality = false; final int quality = videoQualities.get(userSelectedQualityIndex); Logger.printDebug(() -> "User changed default quality to: " + quality); changeDefaultQuality(quality); return userSelectedQualityIndex; } // find the highest quality that is equal to or less than the preferred int qualityToUse = videoQualities.get(0); // first element is automatic mode int qualityIndexToUse = 0; int i = 0; for (Integer quality : videoQualities) { if (quality <= preferredQuality && qualityToUse < quality) { qualityToUse = quality; qualityIndexToUse = i; } i++; } // If the desired quality index is equal to the original index, // then the video is already set to the desired default quality. // // The method could return here, but the UI video quality flyout will still // show 'Auto' (ie: Auto (480p)) // It appears that "Auto" picks the resolution on video load, // and it does not appear to change the resolution during playback. // // To prevent confusion, set the video index anyways (even if it matches the existing index) // As that will force the UI picker to not display "Auto" which may confuse the user. if (qualityIndexToUse == originalQualityIndex) { Logger.printDebug(() -> "Video is already preferred quality: " + preferredQuality); } else { final int qualityToUseLog = qualityToUse; Logger.printDebug(() -> "Quality changed from: " + videoQualities.get(originalQualityIndex) + " to: " + qualityToUseLog); } Method m = qInterface.getClass().getMethod(qIndexMethod, Integer.TYPE); m.invoke(qInterface, qualityToUse); return qualityIndexToUse; } catch (Exception ex) { Logger.printException(() -> "Failed to set quality", ex); return originalQualityIndex; } } /** * Injection point. Old quality menu. */ public static void userChangedQuality(int selectedQualityIndex) { if (!Settings.REMEMBER_VIDEO_QUALITY_LAST_SELECTED.get()) return; userSelectedQualityIndex = selectedQualityIndex; userChangedDefaultQuality = true; } /** * Injection point. New quality menu. */ public static void userChangedQualityInNewFlyout(int selectedQuality) { if (!Settings.REMEMBER_VIDEO_QUALITY_LAST_SELECTED.get()) return; changeDefaultQuality(selectedQuality); // Quality is human readable resolution (ie: 1080). } /** * Injection point. */ public static void newVideoStarted(Object ignoredPlayerController) { Logger.printDebug(() -> "newVideoStarted"); qualityNeedsUpdating = true; videoQualities = null; } }
6,964
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
RestoreOldVideoQualityMenuPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/playback/quality/RestoreOldVideoQualityMenuPatch.java
package app.revanced.integrations.youtube.patches.playback.quality; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import app.revanced.integrations.youtube.patches.components.VideoQualityMenuFilterPatch; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.shared.Logger; /** * This patch contains the logic to show the old video quality menu. * Two methods are required, because the quality menu is a RecyclerView in the new YouTube version * and a ListView in the old one. */ @SuppressWarnings("unused") public final class RestoreOldVideoQualityMenuPatch { /** * Injection point. */ public static void onFlyoutMenuCreate(RecyclerView recyclerView) { if (!Settings.RESTORE_OLD_VIDEO_QUALITY_MENU.get()) return; recyclerView.getViewTreeObserver().addOnDrawListener(() -> { try { // Check if the current view is the quality menu. if (VideoQualityMenuFilterPatch.isVideoQualityMenuVisible) { VideoQualityMenuFilterPatch.isVideoQualityMenuVisible = false; ((ViewGroup) recyclerView.getParent().getParent().getParent()).setVisibility(View.GONE); View advancedQualityView = ((ViewGroup) recyclerView.getChildAt(0)).getChildAt(3); if (advancedQualityView != null) { // Click the "Advanced" quality menu to show the "old" quality menu. advancedQualityView.setSoundEffectsEnabled(false); advancedQualityView.performClick(); } } } catch (Exception ex) { Logger.printException(() -> "onFlyoutMenuCreate failure", ex); } }); } /** * Injection point. Only used if spoofing to an old app version. */ public static void showOldVideoQualityMenu(final ListView listView) { if (!Settings.RESTORE_OLD_VIDEO_QUALITY_MENU.get()) return; listView.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() { @Override public void onChildViewAdded(View parent, View child) { Logger.printDebug(() -> "Added listener to old type of quality menu"); parent.setVisibility(View.GONE); final var indexOfAdvancedQualityMenuItem = 4; if (listView.indexOfChild(child) != indexOfAdvancedQualityMenuItem) return; Logger.printDebug(() -> "Found advanced menu item in old type of quality menu"); final var qualityItemMenuPosition = 4; listView.performItemClick(null, qualityItemMenuPosition, 0); } @Override public void onChildViewRemoved(View parent, View child) { } }); } }
2,947
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ThemePatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/theme/ThemePatch.java
package app.revanced.integrations.youtube.patches.theme; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.youtube.ThemeHelper; @SuppressWarnings("unused") public class ThemePatch { // color constants used in relation with litho components private static final int[] WHITE_VALUES = { -1, // comments chip background -394759, // music related results panel background -83886081, // video chapters list background }; private static final int[] DARK_VALUES = { -14145496, // explore drawer background -14606047, // comments chip background -15198184, // music related results panel background -15790321, // comments chip background (new layout) -98492127 // video chapters list background }; // background colors private static int whiteColor = 0; private static int blackColor = 0; // Used by app.revanced.patches.youtube.layout.theme.patch.LithoThemePatch /** * Change the color of Litho components. * If the color of the component matches one of the values, return the background color . * * @param originalValue The original color value. * @return The new or original color value */ public static int getValue(int originalValue) { if (ThemeHelper.isDarkTheme()) { if (anyEquals(originalValue, DARK_VALUES)) return getBlackColor(); } else { if (anyEquals(originalValue, WHITE_VALUES)) return getWhiteColor(); } return originalValue; } public static boolean gradientLoadingScreenEnabled() { return Settings.GRADIENT_LOADING_SCREEN.get(); } private static int getBlackColor() { if (blackColor == 0) blackColor = Utils.getResourceColor("yt_black1"); return blackColor; } private static int getWhiteColor() { if (whiteColor == 0) whiteColor = Utils.getResourceColor("yt_white1"); return whiteColor; } private static boolean anyEquals(int value, int... of) { for (int v : of) if (value == v) return true; return false; } }
2,235
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
SeekbarColorPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/theme/SeekbarColorPatch.java
package app.revanced.integrations.youtube.patches.theme; import static app.revanced.integrations.shared.StringRef.str; import android.graphics.Color; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; @SuppressWarnings("unused") public final class SeekbarColorPatch { private static final boolean USE_SEEKBAR_CUSTOM_COLOR = Settings.SEEKBAR_CUSTOM_COLOR.get(); /** * Default color of the seekbar. */ private static final int ORIGINAL_SEEKBAR_COLOR = 0xFFFF0000; /** * Default YouTube seekbar color brightness. */ private static final float ORIGINAL_SEEKBAR_COLOR_BRIGHTNESS; /** * If {@link Settings#SEEKBAR_CUSTOM_COLOR} is enabled, * this is the color value of {@link Settings#SEEKBAR_CUSTOM_COLOR_VALUE}. * Otherwise this is {@link #ORIGINAL_SEEKBAR_COLOR}. */ private static int seekbarColor = ORIGINAL_SEEKBAR_COLOR; /** * Custom seekbar hue, saturation, and brightness values. */ private static final float[] customSeekbarColorHSV = new float[3]; static { float[] hsv = new float[3]; Color.colorToHSV(ORIGINAL_SEEKBAR_COLOR, hsv); ORIGINAL_SEEKBAR_COLOR_BRIGHTNESS = hsv[2]; if (USE_SEEKBAR_CUSTOM_COLOR) { loadCustomSeekbarColor(); } } private static void loadCustomSeekbarColor() { try { seekbarColor = Color.parseColor(Settings.SEEKBAR_CUSTOM_COLOR_VALUE.get()); Color.colorToHSV(seekbarColor, customSeekbarColorHSV); } catch (Exception ex) { Utils.showToastShort(str("revanced_seekbar_custom_color_invalid")); Settings.SEEKBAR_CUSTOM_COLOR_VALUE.resetToDefault(); loadCustomSeekbarColor(); } } public static int getSeekbarColor() { return seekbarColor; } /** * Injection point. * * Overrides all Litho components that use the YouTube seekbar color. * Used only for the video thumbnails seekbar. * * If {@link Settings#HIDE_SEEKBAR_THUMBNAIL} is enabled, this returns a fully transparent color. */ public static int getLithoColor(int colorValue) { if (colorValue == ORIGINAL_SEEKBAR_COLOR) { if (Settings.HIDE_SEEKBAR_THUMBNAIL.get()) { return 0x00000000; } return getSeekbarColorValue(ORIGINAL_SEEKBAR_COLOR); } return colorValue; } /** * Injection point. * * Overrides color when video player seekbar is clicked. */ public static int getVideoPlayerSeekbarClickedColor(int colorValue) { return colorValue == ORIGINAL_SEEKBAR_COLOR ? getSeekbarColorValue(ORIGINAL_SEEKBAR_COLOR) : colorValue; } /** * Injection point. * * Overrides color used for the video player seekbar. */ public static int getVideoPlayerSeekbarColor(int originalColor) { return getSeekbarColorValue(originalColor); } /** * Color parameter is changed to the custom seekbar color, while retaining * the brightness and alpha changes of the parameter value compared to the original seekbar color. */ private static int getSeekbarColorValue(int originalColor) { try { if (!USE_SEEKBAR_CUSTOM_COLOR || originalColor == seekbarColor) { return originalColor; // nothing to do } final int alphaDifference = Color.alpha(originalColor) - Color.alpha(ORIGINAL_SEEKBAR_COLOR); // The seekbar uses the same color but different brightness for different situations. float[] hsv = new float[3]; Color.colorToHSV(originalColor, hsv); final float brightnessDifference = hsv[2] - ORIGINAL_SEEKBAR_COLOR_BRIGHTNESS; // Apply the brightness difference to the custom seekbar color. hsv[0] = customSeekbarColorHSV[0]; hsv[1] = customSeekbarColorHSV[1]; hsv[2] = clamp(customSeekbarColorHSV[2] + brightnessDifference, 0, 1); final int replacementAlpha = clamp(Color.alpha(seekbarColor) + alphaDifference, 0, 255); final int replacementColor = Color.HSVToColor(replacementAlpha, hsv); Logger.printDebug(() -> String.format("Original color: #%08X replacement color: #%08X", originalColor, replacementColor)); return replacementColor; } catch (Exception ex) { Logger.printException(() -> "getSeekbarColorValue failure", ex); return originalColor; } } static int clamp(int value, int lower, int upper) { return Math.max(lower, Math.min(value, upper)); } static float clamp(float value, float lower, float upper) { return Math.max(lower, Math.min(value, upper)); } }
4,965
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ProgressBarDrawable.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/theme/ProgressBarDrawable.java
package app.revanced.integrations.youtube.patches.theme; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import app.revanced.integrations.youtube.patches.HideSeekbarPatch; import app.revanced.integrations.youtube.settings.Settings; /** * Used by {@link SeekbarColorPatch} change the color of the seekbar. * and {@link HideSeekbarPatch} to hide the seekbar of the feed and watch history. */ @SuppressWarnings("unused") public class ProgressBarDrawable extends Drawable { private final Paint paint = new Paint(); @Override public void draw(@NonNull Canvas canvas) { if (Settings.HIDE_SEEKBAR_THUMBNAIL.get()) { return; } paint.setColor(SeekbarColorPatch.getSeekbarColor()); canvas.drawRect(getBounds(), paint); } @Override public void setAlpha(int alpha) { paint.setAlpha(alpha); } @Override public void setColorFilter(@Nullable ColorFilter colorFilter) { paint.setColorFilter(colorFilter); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } }
1,301
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
StoryboardRenderer.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/spoof/StoryboardRenderer.java
package app.revanced.integrations.youtube.patches.spoof; import androidx.annotation.Nullable; import org.jetbrains.annotations.NotNull; @Deprecated public final class StoryboardRenderer { @Nullable private final String spec; private final boolean isLiveStream; @Nullable private final Integer recommendedLevel; public StoryboardRenderer(@Nullable String spec, boolean isLiveStream, @Nullable Integer recommendedLevel) { this.spec = spec; this.isLiveStream = isLiveStream; this.recommendedLevel = recommendedLevel; } @Nullable public String getSpec() { return spec; } public boolean isLiveStream() { return isLiveStream; } /** * @return Recommended image quality level, or NULL if no recommendation exists. */ @Nullable public Integer getRecommendedLevel() { return recommendedLevel; } @NotNull @Override public String toString() { return "StoryboardRenderer{" + "isLiveStream=" + isLiveStream + ", spec='" + spec + '\'' + ", recommendedLevel=" + recommendedLevel + '}'; } }
1,192
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
SpoofDeviceDimensionsPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/spoof/SpoofDeviceDimensionsPatch.java
package app.revanced.integrations.youtube.patches.spoof; import app.revanced.integrations.youtube.settings.Settings; @SuppressWarnings("unused") public class SpoofDeviceDimensionsPatch { private static final boolean SPOOF = Settings.SPOOF_DEVICE_DIMENSIONS.get(); public static int getMinHeightOrWidth(int minHeightOrWidth) { return SPOOF ? 64 : minHeightOrWidth; } public static int getMaxHeightOrWidth(int maxHeightOrWidth) { return SPOOF ? 4096 : maxHeightOrWidth; } }
513
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
SpoofSignaturePatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/spoof/SpoofSignaturePatch.java
package app.revanced.integrations.youtube.patches.spoof; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.Nullable; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.youtube.patches.VideoInformation; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.youtube.shared.PlayerType; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static app.revanced.integrations.shared.Utils.containsAny; import static app.revanced.integrations.youtube.patches.spoof.requests.StoryboardRendererRequester.getStoryboardRenderer; /** @noinspection unused*/ @Deprecated public class SpoofSignaturePatch { /** * Parameter (also used by * <a href="https://github.com/yt-dlp/yt-dlp/blob/81ca451480051d7ce1a31c017e005358345a9149/yt_dlp/extractor/youtube.py#L3602">yt-dlp</a>) * to fix playback issues. */ private static final String INCOGNITO_PARAMETERS = "CgIQBg=="; /** * Parameters used when playing clips. */ private static final String CLIPS_PARAMETERS = "kAIB"; /** * Parameters causing playback issues. */ private static final String[] AUTOPLAY_PARAMETERS = { "YAHI", // Autoplay in feed. "SAFg" // Autoplay in scrim. }; /** * Parameter used for autoplay in scrim. * Prepend this parameter to mute video playback (for autoplay in feed). */ private static final String SCRIM_PARAMETER = "SAFgAXgB"; /** * Last video id loaded. Used to prevent reloading the same spec multiple times. */ @Nullable private static volatile String lastPlayerResponseVideoId; @Nullable private static volatile Future<StoryboardRenderer> rendererFuture; private static volatile boolean useOriginalStoryboardRenderer; private static volatile boolean isPlayingShorts; @Nullable private static StoryboardRenderer getRenderer(boolean waitForCompletion) { Future<StoryboardRenderer> future = rendererFuture; if (future != null) { try { if (waitForCompletion || future.isDone()) { return future.get(20000, TimeUnit.MILLISECONDS); // Any arbitrarily large timeout. } // else, return null. } catch (TimeoutException ex) { Logger.printDebug(() -> "Could not get renderer (get timed out)"); } catch (ExecutionException | InterruptedException ex) { // Should never happen. Logger.printException(() -> "Could not get renderer", ex); } } return null; } /** * Injection point. * * Called off the main thread, and called multiple times for each video. * * @param parameters Original protobuf parameter value. */ public static String spoofParameter(String parameters, boolean isShortAndOpeningOrPlaying) { try { Logger.printDebug(() -> "Original protobuf parameter value: " + parameters); if (parameters == null || !Settings.SPOOF_SIGNATURE.get()) { return parameters; } // Clip's player parameters contain a lot of information (e.g. video start and end time or whether it loops) // For this reason, the player parameters of a clip are usually very long (150~300 characters). // Clips are 60 seconds or less in length, so no spoofing. //noinspection AssignmentUsedAsCondition if (useOriginalStoryboardRenderer = parameters.length() > 150 || parameters.startsWith(CLIPS_PARAMETERS)) { return parameters; } // Shorts do not need to be spoofed. //noinspection AssignmentUsedAsCondition if (useOriginalStoryboardRenderer = VideoInformation.playerParametersAreShort(parameters)) { isPlayingShorts = true; return parameters; } isPlayingShorts = false; boolean isPlayingFeed = PlayerType.getCurrent() == PlayerType.INLINE_MINIMAL && containsAny(parameters, AUTOPLAY_PARAMETERS); if (isPlayingFeed) { //noinspection AssignmentUsedAsCondition if (useOriginalStoryboardRenderer = !Settings.SPOOF_SIGNATURE_IN_FEED.get()) { // Don't spoof the feed video playback. This will cause video playback issues, // but only if user continues watching for more than 1 minute. return parameters; } // Spoof the feed video. Video will show up in watch history and video subtitles are missing. fetchStoryboardRenderer(); return SCRIM_PARAMETER + INCOGNITO_PARAMETERS; } fetchStoryboardRenderer(); } catch (Exception ex) { Logger.printException(() -> "spoofParameter failure", ex); } return INCOGNITO_PARAMETERS; } private static void fetchStoryboardRenderer() { if (!Settings.SPOOF_STORYBOARD_RENDERER.get()) { lastPlayerResponseVideoId = null; rendererFuture = null; return; } String videoId = VideoInformation.getPlayerResponseVideoId(); if (!videoId.equals(lastPlayerResponseVideoId)) { rendererFuture = Utils.submitOnBackgroundThread(() -> getStoryboardRenderer(videoId)); lastPlayerResponseVideoId = videoId; } // Block until the renderer fetch completes. // This is desired because if this returns without finishing the fetch // then video will start playback but the storyboard is not ready yet. getRenderer(true); } private static String getStoryboardRendererSpec(String originalStoryboardRendererSpec, boolean returnNullIfLiveStream) { if (Settings.SPOOF_SIGNATURE.get() && !useOriginalStoryboardRenderer) { StoryboardRenderer renderer = getRenderer(false); if (renderer != null) { if (returnNullIfLiveStream && renderer.isLiveStream()) { return null; } String spec = renderer.getSpec(); if (spec != null) { return spec; } } } return originalStoryboardRendererSpec; } /** * Injection point. * Called from background threads and from the main thread. */ @Nullable public static String getStoryboardRendererSpec(String originalStoryboardRendererSpec) { return getStoryboardRendererSpec(originalStoryboardRendererSpec, false); } /** * Injection point. * Uses additional check to handle live streams. * Called from background threads and from the main thread. */ @Nullable public static String getStoryboardDecoderRendererSpec(String originalStoryboardRendererSpec) { return getStoryboardRendererSpec(originalStoryboardRendererSpec, true); } /** * Injection point. */ public static int getRecommendedLevel(int originalLevel) { if (Settings.SPOOF_SIGNATURE.get() && !useOriginalStoryboardRenderer) { StoryboardRenderer renderer = getRenderer(false); if (renderer != null) { Integer recommendedLevel = renderer.getRecommendedLevel(); if (recommendedLevel != null) return recommendedLevel; } } return originalLevel; } /** * Injection point. Forces seekbar to be shown for paid videos or * if {@link Settings#SPOOF_STORYBOARD_RENDERER} is not enabled. */ public static boolean getSeekbarThumbnailOverrideValue() { if (!Settings.SPOOF_SIGNATURE.get()) { return false; } StoryboardRenderer renderer = getRenderer(false); if (renderer == null) { // Spoof storyboard renderer is turned off, // video is paid, or the storyboard fetch timed out. // Show empty thumbnails so the seek time and chapters still show up. return true; } return renderer.getSpec() != null; } /** * Injection point. * * @param view seekbar thumbnail view. Includes both shorts and regular videos. */ public static void seekbarImageViewCreated(ImageView view) { try { if (!Settings.SPOOF_SIGNATURE.get() || Settings.SPOOF_STORYBOARD_RENDERER.get()) { return; } if (isPlayingShorts) return; view.setVisibility(View.GONE); // Also hide the border around the thumbnail (otherwise a 1 pixel wide bordered frame is visible). ViewGroup parentLayout = (ViewGroup) view.getParent(); parentLayout.setPadding(0, 0, 0, 0); } catch (Exception ex) { Logger.printException(() -> "seekbarImageViewCreated failure", ex); } } }
9,329
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
SpoofAppVersionPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/spoof/SpoofAppVersionPatch.java
package app.revanced.integrations.youtube.patches.spoof; import app.revanced.integrations.youtube.settings.Settings; @SuppressWarnings("unused") public class SpoofAppVersionPatch { private static final boolean SPOOF_APP_VERSION_ENABLED = Settings.SPOOF_APP_VERSION.get(); private static final String SPOOF_APP_VERSION_TARGET = Settings.SPOOF_APP_VERSION_TARGET.get(); /** * Injection point */ public static String getYouTubeVersionOverride(String version) { if (SPOOF_APP_VERSION_ENABLED) return SPOOF_APP_VERSION_TARGET; return version; } public static boolean isSpoofingToLessThan(String version) { return SPOOF_APP_VERSION_ENABLED && SPOOF_APP_VERSION_TARGET.compareTo(version) < 0; } }
758
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
StoryboardRendererRequester.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/spoof/requests/StoryboardRendererRequester.java
package app.revanced.integrations.youtube.patches.spoof.requests; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import app.revanced.integrations.shared.settings.BaseSettings; import app.revanced.integrations.youtube.patches.spoof.StoryboardRenderer; import app.revanced.integrations.youtube.requests.Requester; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.nio.charset.StandardCharsets; import java.util.Objects; import static app.revanced.integrations.shared.StringRef.str; import static app.revanced.integrations.youtube.patches.spoof.requests.PlayerRoutes.*; @Deprecated public class StoryboardRendererRequester { /** * For videos that have no storyboard. * Usually for low resolution videos as old as YouTube itself. * Does not include paid videos where the renderer fetch fails. */ private static final StoryboardRenderer emptyStoryboard = new StoryboardRenderer(null, false, null); private StoryboardRendererRequester() { } private static void randomlyWaitIfLocallyDebugging() { final boolean randomlyWait = false; // Enable to simulate slow connection responses. if (randomlyWait) { final long maximumTimeToRandomlyWait = 10000; Utils.doNothingForDuration(maximumTimeToRandomlyWait); } } private static void handleConnectionError(@NonNull String toastMessage, @Nullable Exception ex, boolean showToastOnIOException) { if (showToastOnIOException) Utils.showToastShort(toastMessage); Logger.printInfo(() -> toastMessage, ex); } @Nullable private static JSONObject fetchPlayerResponse(@NonNull String requestBody, boolean showToastOnIOException) { final long startTime = System.currentTimeMillis(); try { Utils.verifyOffMainThread(); Objects.requireNonNull(requestBody); final byte[] innerTubeBody = requestBody.getBytes(StandardCharsets.UTF_8); HttpURLConnection connection = PlayerRoutes.getPlayerResponseConnectionFromRoute(GET_STORYBOARD_SPEC_RENDERER); connection.getOutputStream().write(innerTubeBody, 0, innerTubeBody.length); final int responseCode = connection.getResponseCode(); randomlyWaitIfLocallyDebugging(); if (responseCode == 200) return Requester.parseJSONObject(connection); // Always show a toast for this, as a non 200 response means something is broken. // Not a normal code path and should not be reached, so no translations are needed. handleConnectionError("Spoof storyboard not available: " + responseCode, null, showToastOnIOException || BaseSettings.DEBUG_TOAST_ON_ERROR.get()); connection.disconnect(); } catch (SocketTimeoutException ex) { handleConnectionError(str("revanced_spoof_storyboard_timeout"), ex, showToastOnIOException); } catch (IOException ex) { handleConnectionError(str("revanced_spoof_storyboard_io_exception", ex.getMessage()), ex, showToastOnIOException); } catch (Exception ex) { Logger.printException(() -> "Spoof storyboard fetch failed", ex); // Should never happen. } finally { Logger.printDebug(() -> "Request took: " + (System.currentTimeMillis() - startTime) + "ms"); } return null; } private static boolean isPlayabilityStatusOk(@NonNull JSONObject playerResponse) { try { return playerResponse.getJSONObject("playabilityStatus").getString("status").equals("OK"); } catch (JSONException e) { Logger.printDebug(() -> "Failed to get playabilityStatus for response: " + playerResponse); } return false; } /** * Fetches the storyboardRenderer from the innerTubeBody. * @param innerTubeBody The innerTubeBody to use to fetch the storyboardRenderer. * @return StoryboardRenderer or null if playabilityStatus is not OK. */ @Nullable private static StoryboardRenderer getStoryboardRendererUsingBody(@NonNull String innerTubeBody, boolean showToastOnIOException) { final JSONObject playerResponse = fetchPlayerResponse(innerTubeBody, showToastOnIOException); if (playerResponse != null && isPlayabilityStatusOk(playerResponse)) return getStoryboardRendererUsingResponse(playerResponse); return null; } @Nullable private static StoryboardRenderer getStoryboardRendererUsingResponse(@NonNull JSONObject playerResponse) { try { Logger.printDebug(() -> "Parsing response: " + playerResponse); if (!playerResponse.has("storyboards")) { Logger.printDebug(() -> "Using empty storyboard"); return emptyStoryboard; } final JSONObject storyboards = playerResponse.getJSONObject("storyboards"); final boolean isLiveStream = storyboards.has("playerLiveStoryboardSpecRenderer"); final String storyboardsRendererTag = isLiveStream ? "playerLiveStoryboardSpecRenderer" : "playerStoryboardSpecRenderer"; final var rendererElement = storyboards.getJSONObject(storyboardsRendererTag); StoryboardRenderer renderer = new StoryboardRenderer( rendererElement.getString("spec"), isLiveStream, rendererElement.has("recommendedLevel") ? rendererElement.getInt("recommendedLevel") : null ); Logger.printDebug(() -> "Fetched: " + renderer); return renderer; } catch (JSONException e) { Logger.printException(() -> "Failed to get storyboardRenderer", e); } return null; } @Nullable public static StoryboardRenderer getStoryboardRenderer(@NonNull String videoId) { Objects.requireNonNull(videoId); var renderer = getStoryboardRendererUsingBody( String.format(ANDROID_INNER_TUBE_BODY, videoId), false); if (renderer == null) { Logger.printDebug(() -> videoId + " not available using Android client"); renderer = getStoryboardRendererUsingBody( String.format(TV_EMBED_INNER_TUBE_BODY, videoId, videoId), true); if (renderer == null) { Logger.printDebug(() -> videoId + " not available using TV embedded client"); } } return renderer; } }
6,950
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
PlayerRoutes.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/spoof/requests/PlayerRoutes.java
package app.revanced.integrations.youtube.patches.spoof.requests; import app.revanced.integrations.youtube.requests.Requester; import app.revanced.integrations.youtube.requests.Route; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.HttpURLConnection; @Deprecated final class PlayerRoutes { private static final String YT_API_URL = "https://www.youtube.com/youtubei/v1/"; static final Route.CompiledRoute GET_STORYBOARD_SPEC_RENDERER = new Route( Route.Method.POST, "player" + "?fields=storyboards.playerStoryboardSpecRenderer," + "storyboards.playerLiveStoryboardSpecRenderer," + "playabilityStatus.status" ).compile(); static final String ANDROID_INNER_TUBE_BODY; static final String TV_EMBED_INNER_TUBE_BODY; /** * TCP connection and HTTP read timeout */ private static final int CONNECTION_TIMEOUT_MILLISECONDS = 4 * 1000; // 4 Seconds. static { JSONObject innerTubeBody = new JSONObject(); try { JSONObject context = new JSONObject(); JSONObject client = new JSONObject(); client.put("clientName", "ANDROID"); client.put("clientVersion", Utils.getAppVersionName()); client.put("androidSdkVersion", 34); context.put("client", client); innerTubeBody.put("context", context); innerTubeBody.put("videoId", "%s"); } catch (JSONException e) { Logger.printException(() -> "Failed to create innerTubeBody", e); } ANDROID_INNER_TUBE_BODY = innerTubeBody.toString(); JSONObject tvEmbedInnerTubeBody = new JSONObject(); try { JSONObject context = new JSONObject(); JSONObject client = new JSONObject(); client.put("clientName", "TVHTML5_SIMPLY_EMBEDDED_PLAYER"); client.put("clientVersion", "2.0"); client.put("platform", "TV"); client.put("clientScreen", "EMBED"); JSONObject thirdParty = new JSONObject(); thirdParty.put("embedUrl", "https://www.youtube.com/watch?v=%s"); context.put("thirdParty", thirdParty); context.put("client", client); tvEmbedInnerTubeBody.put("context", context); tvEmbedInnerTubeBody.put("videoId", "%s"); } catch (JSONException e) { Logger.printException(() -> "Failed to create tvEmbedInnerTubeBody", e); } TV_EMBED_INNER_TUBE_BODY = tvEmbedInnerTubeBody.toString(); } private PlayerRoutes() { } /** @noinspection SameParameterValue*/ static HttpURLConnection getPlayerResponseConnectionFromRoute(Route.CompiledRoute route) throws IOException { var connection = Requester.getConnectionFromCompiledRoute(YT_API_URL, route); connection.setRequestProperty( "User-Agent", "com.google.android.youtube/" + Utils.getAppVersionName() + " (Linux; U; Android 12; GB) gzip" ); connection.setRequestProperty("X-Goog-Api-Format-Version", "2"); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setConnectTimeout(CONNECTION_TIMEOUT_MILLISECONDS); connection.setReadTimeout(CONNECTION_TIMEOUT_MILLISECONDS); return connection; } }
3,638
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
AnnouncementsPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/announcements/AnnouncementsPatch.java
package app.revanced.integrations.youtube.patches.announcements; import android.app.Activity; import android.os.Build; import android.text.Html; import android.text.method.LinkMovementMethod; import android.widget.TextView; import androidx.annotation.RequiresApi; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.youtube.patches.announcements.requests.AnnouncementsRoutes; import app.revanced.integrations.youtube.requests.Requester; import app.revanced.integrations.youtube.settings.Settings; import org.json.JSONObject; import java.io.IOException; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Locale; import static android.text.Html.FROM_HTML_MODE_COMPACT; import static app.revanced.integrations.shared.StringRef.str; import static app.revanced.integrations.youtube.patches.announcements.requests.AnnouncementsRoutes.GET_LATEST_ANNOUNCEMENT; @SuppressWarnings("unused") public final class AnnouncementsPatch { private AnnouncementsPatch() { } @RequiresApi(api = Build.VERSION_CODES.O) public static void showAnnouncement(final Activity context) { if (!Settings.ANNOUNCEMENTS.get()) return; // Check if there is internet connection if (!Utils.isNetworkConnected()) return; Utils.runOnBackgroundThread(() -> { try { HttpURLConnection connection = AnnouncementsRoutes.getAnnouncementsConnectionFromRoute( GET_LATEST_ANNOUNCEMENT, Locale.getDefault().toLanguageTag()); Logger.printDebug(() -> "Get latest announcement route connection url: " + connection.getURL()); try { // Do not show the announcement if the request failed. if (connection.getResponseCode() != 200) { if (Settings.ANNOUNCEMENT_LAST_ID.isSetToDefault()) return; Settings.ANNOUNCEMENT_LAST_ID.resetToDefault(); Utils.showToastLong(str("revanced_announcements_connection_failed")); return; } } catch (IOException ex) { final var message = "Failed connecting to announcements provider"; Logger.printException(() -> message, ex); return; } var jsonString = Requester.parseStringAndDisconnect(connection); // Parse the announcement. Fall-back to raw string if it fails. int id = Settings.ANNOUNCEMENT_LAST_ID.defaultValue; String title; String message; Level level = Level.INFO; try { final var announcement = new JSONObject(jsonString); id = announcement.getInt("id"); title = announcement.getString("title"); message = announcement.getJSONObject("content").getString("message"); if (!announcement.isNull("level")) level = Level.fromInt(announcement.getInt("level")); } catch (Throwable ex) { Logger.printException(() -> "Failed to parse announcement. Fall-backing to raw string", ex); title = "Announcement"; message = jsonString; } // TODO: Remove this migration code after a few months. if (!Settings.DEPRECATED_ANNOUNCEMENT_LAST_HASH.isSetToDefault()){ final byte[] hashBytes = MessageDigest .getInstance("SHA-256") .digest(jsonString.getBytes(StandardCharsets.UTF_8)); final var hash = java.util.Base64.getEncoder().encodeToString(hashBytes); // Migrate to saving the id instead of the hash. if (hash.equals(Settings.DEPRECATED_ANNOUNCEMENT_LAST_HASH.get())) { Settings.ANNOUNCEMENT_LAST_ID.save(id); } Settings.DEPRECATED_ANNOUNCEMENT_LAST_HASH.resetToDefault(); } // Do not show the announcement, if the last announcement id is the same as the current one. if (Settings.ANNOUNCEMENT_LAST_ID.get() == id) return; int finalId = id; final var finalTitle = title; final var finalMessage = Html.fromHtml(message, FROM_HTML_MODE_COMPACT); final Level finalLevel = level; Utils.runOnMainThread(() -> { // Show the announcement. var alertDialog = new android.app.AlertDialog.Builder(context) .setTitle(finalTitle) .setMessage(finalMessage) .setIcon(finalLevel.icon) .setPositiveButton(android.R.string.ok, (dialog, which) -> { Settings.ANNOUNCEMENT_LAST_ID.save(finalId); dialog.dismiss(); }).setNegativeButton(str("revanced_announcements_dialog_dismiss"), (dialog, which) -> { dialog.dismiss(); }) .setCancelable(false) .show(); // Make links clickable. ((TextView)alertDialog.findViewById(android.R.id.message)) .setMovementMethod(LinkMovementMethod.getInstance()); }); } catch (Exception e) { final var message = "Failed to get announcement"; Logger.printException(() -> message, e); } }); } // TODO: Use better icons. private enum Level { INFO(android.R.drawable.ic_dialog_info), WARNING(android.R.drawable.ic_dialog_alert), SEVERE(android.R.drawable.ic_dialog_alert); public final int icon; Level(int icon) { this.icon = icon; } public static Level fromInt(int value) { return values()[Math.min(value, values().length - 1)]; } } }
6,380
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
AnnouncementsRoutes.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/announcements/requests/AnnouncementsRoutes.java
package app.revanced.integrations.youtube.patches.announcements.requests; import app.revanced.integrations.youtube.requests.Requester; import app.revanced.integrations.youtube.requests.Route; import java.io.IOException; import java.net.HttpURLConnection; import static app.revanced.integrations.youtube.requests.Route.Method.GET; public class AnnouncementsRoutes { private static final String ANNOUNCEMENTS_PROVIDER = "https://api.revanced.app/v2"; /** * 'language' parameter is IETF format (for USA it would be 'en-us'). */ public static final Route GET_LATEST_ANNOUNCEMENT = new Route(GET, "/announcements/youtube/latest?language={language}"); private AnnouncementsRoutes() { } public static HttpURLConnection getAnnouncementsConnectionFromRoute(Route route, String... params) throws IOException { return Requester.getConnectionFromRoute(ANNOUNCEMENTS_PROVIDER, route, params); } }
936
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
AdsFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/AdsFilter.java
package app.revanced.integrations.youtube.patches.components; import static app.revanced.integrations.shared.StringRef.str; import android.app.Instrumentation; import android.view.KeyEvent; import android.view.View; import androidx.annotation.Nullable; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.youtube.StringTrieSearch; @SuppressWarnings("unused") public final class AdsFilter extends Filter { // region Fullscreen ad private static volatile long lastTimeClosedFullscreenAd; private static final Instrumentation instrumentation = new Instrumentation(); private final StringFilterGroup fullscreenAd; // endregion private final StringTrieSearch exceptions = new StringTrieSearch(); private final StringFilterGroup shoppingLinks; public AdsFilter() { exceptions.addPatterns( "home_video_with_context", // Don't filter anything in the home page video component. "related_video_with_context", // Don't filter anything in the related video component. "comment_thread", // Don't filter anything in the comments. "|comment.", // Don't filter anything in the comments replies. "library_recent_shelf" ); // Identifiers. final var carouselAd = new StringFilterGroup( Settings.HIDE_GENERAL_ADS, "carousel_ad" ); addIdentifierCallbacks(carouselAd); // Paths. fullscreenAd = new StringFilterGroup( Settings.HIDE_FULLSCREEN_ADS, "_interstitial" ); final var buttonedAd = new StringFilterGroup( Settings.HIDE_BUTTONED_ADS, "_buttoned_layout", "full_width_square_image_layout", "_ad_with", "text_image_button_group_layout", "video_display_button_group_layout", "landscape_image_wide_button_layout", "video_display_carousel_button_group_layout" ); final var generalAds = new StringFilterGroup( Settings.HIDE_GENERAL_ADS, "ads_video_with_context", "banner_text_icon", "square_image_layout", "watch_metadata_app_promo", "video_display_full_layout", "hero_promo_image", "statement_banner", "carousel_footered_layout", "text_image_button_layout", "primetime_promo", "product_details", "carousel_headered_layout", "full_width_portrait_image_layout", "brand_video_shelf" ); final var movieAds = new StringFilterGroup( Settings.HIDE_MOVIES_SECTION, "browsy_bar", "compact_movie", "horizontal_movie_shelf", "movie_and_show_upsell_card", "compact_tvfilm_item", "offer_module_root" ); final var viewProducts = new StringFilterGroup( Settings.HIDE_PRODUCTS_BANNER, "product_item", "products_in_video" ); shoppingLinks = new StringFilterGroup( Settings.HIDE_SHOPPING_LINKS, "expandable_list" ); final var webLinkPanel = new StringFilterGroup( Settings.HIDE_WEB_SEARCH_RESULTS, "web_link_panel" ); final var merchandise = new StringFilterGroup( Settings.HIDE_MERCHANDISE_BANNERS, "product_carousel" ); final var selfSponsor = new StringFilterGroup( Settings.HIDE_SELF_SPONSOR, "cta_shelf_card" ); addPathCallbacks( generalAds, buttonedAd, merchandise, viewProducts, selfSponsor, fullscreenAd, webLinkPanel, shoppingLinks, movieAds ); } @Override boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { if (exceptions.matches(path)) return false; if (matchedGroup == fullscreenAd) { if (path.contains("|ImageType|")) closeFullscreenAd(); return false; // Do not actually filter the fullscreen ad otherwise it will leave a dimmed screen. } // Check for the index because of likelihood of false positives. if (matchedGroup == shoppingLinks && contentIndex != 0) return false; return super.isFiltered(identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex); } /** * Hide the view, which shows ads in the homepage. * * @param view The view, which shows ads. */ public static void hideAdAttributionView(View view) { Utils.hideViewBy1dpUnderCondition(Settings.HIDE_GENERAL_ADS, view); } /** * Close the fullscreen ad. * <p> * The strategy is to send a back button event to the app to close the fullscreen ad using the back button event. */ private static void closeFullscreenAd() { final var currentTime = System.currentTimeMillis(); // Prevent spamming the back button. if (currentTime - lastTimeClosedFullscreenAd < 10000) return; lastTimeClosedFullscreenAd = currentTime; Logger.printDebug(() -> "Closing fullscreen ad"); Utils.runOnMainThreadDelayed(() -> { // Must run off main thread (Odd, but whatever). Utils.runOnBackgroundThread(() -> { try { instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); } catch (Exception ex) { // Injecting user events on Android 10+ requires the manifest to include // INJECT_EVENTS, and it's usage is heavily restricted // and requires the user to manually approve the permission in the device settings. // // And no matter what, permissions cannot be added for root installations // as manifest changes are ignored for mount installations. // // Instead, catch the SecurityException and turn off hide full screen ads // since this functionality does not work for these devices. Logger.printInfo(() -> "Could not inject back button event", ex); Settings.HIDE_FULLSCREEN_ADS.save(false); Utils.showToastLong(str("revanced_hide_fullscreen_ads_feature_not_available_toast")); } }); }, 1000); } }
7,117
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
CustomFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/CustomFilter.java
package app.revanced.integrations.youtube.patches.components; import static app.revanced.integrations.shared.StringRef.str; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.youtube.ByteTrieSearch; import app.revanced.integrations.youtube.settings.Settings; /** * Allows custom filtering using a path and optionally a proto buffer string. */ @SuppressWarnings("unused") final class CustomFilter extends Filter { private static void showInvalidSyntaxToast(@NonNull String expression) { Utils.showToastLong(str("revanced_custom_filter_toast_invalid_syntax", expression)); } private static class CustomFilterGroup extends StringFilterGroup { /** * Optional character for the path that indicates the custom filter path must match the start. * Must be the first character of the expression. */ public static final String SYNTAX_STARTS_WITH = "^"; /** * Optional character that separates the path from a proto buffer string pattern. */ public static final String SYNTAX_BUFFER_SYMBOL = "$"; /** * @return the parsed objects */ @NonNull @SuppressWarnings("ConstantConditions") static Collection<CustomFilterGroup> parseCustomFilterGroups() { String rawCustomFilterText = Settings.CUSTOM_FILTER_STRINGS.get(); if (rawCustomFilterText.isBlank()) { return Collections.emptyList(); } // Map key is the path including optional special characters (^ and/or $) Map<String, CustomFilterGroup> result = new HashMap<>(); Pattern pattern = Pattern.compile( "(" // map key group + "(\\Q" + SYNTAX_STARTS_WITH + "\\E?)" // optional starts with + "([^\\Q" + SYNTAX_BUFFER_SYMBOL + "\\E]*)" // path + "(\\Q" + SYNTAX_BUFFER_SYMBOL + "\\E?)" // optional buffer symbol + ")" // end map key group + "(.*)"); // optional buffer string for (String expression : rawCustomFilterText.split("\n")) { if (expression.isBlank()) continue; Matcher matcher = pattern.matcher(expression); if (!matcher.find()) { showInvalidSyntaxToast(expression); continue; } final String mapKey = matcher.group(1); final boolean pathStartsWith = !matcher.group(2).isEmpty(); final String path = matcher.group(3); final boolean hasBufferSymbol = !matcher.group(4).isEmpty(); final String bufferString = matcher.group(5); if (path.isBlank() || (hasBufferSymbol && bufferString.isBlank())) { showInvalidSyntaxToast(expression); continue; } // Use one group object for all expressions with the same path. // This ensures the buffer is searched exactly once // when multiple paths are used with different buffer strings. CustomFilterGroup group = result.get(mapKey); if (group == null) { group = new CustomFilterGroup(pathStartsWith, path); result.put(mapKey, group); } if (hasBufferSymbol) { group.addBufferString(bufferString); } } return result.values(); } final boolean startsWith; ByteTrieSearch bufferSearch; CustomFilterGroup(boolean startsWith, @NonNull String path) { super(Settings.CUSTOM_FILTER, path); this.startsWith = startsWith; } void addBufferString(@NonNull String bufferString) { if (bufferSearch == null) { bufferSearch = new ByteTrieSearch(); } bufferSearch.addPattern(bufferString.getBytes()); } @NonNull @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("CustomFilterGroup{"); builder.append("path="); if (startsWith) builder.append(SYNTAX_STARTS_WITH); builder.append(filters[0]); if (bufferSearch != null) { String delimitingCharacter = "❙"; builder.append(", bufferStrings="); builder.append(delimitingCharacter); for (byte[] bufferString : bufferSearch.getPatterns()) { builder.append(new String(bufferString)); builder.append(delimitingCharacter); } } builder.append("}"); return builder.toString(); } } public CustomFilter() { Collection<CustomFilterGroup> groups = CustomFilterGroup.parseCustomFilterGroups(); if (!groups.isEmpty()) { CustomFilterGroup[] groupsArray = groups.toArray(new CustomFilterGroup[0]); Logger.printDebug(()-> "Using Custom filters: " + Arrays.toString(groupsArray)); addPathCallbacks(groupsArray); } } @Override boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { // All callbacks are custom filter groups. CustomFilterGroup custom = (CustomFilterGroup) matchedGroup; if (custom.startsWith && contentIndex != 0) { return false; } if (custom.bufferSearch != null && !custom.bufferSearch.matches(protobufBufferArray)) { return false; } return super.isFiltered(identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex); } }
6,336
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
CommentsFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/CommentsFilter.java
package app.revanced.integrations.youtube.patches.components; import app.revanced.integrations.youtube.settings.Settings; @SuppressWarnings("unused") final class CommentsFilter extends Filter { public CommentsFilter() { var comments = new StringFilterGroup( Settings.HIDE_COMMENTS_SECTION, "video_metadata_carousel", "_comments" ); var previewComment = new StringFilterGroup( Settings.HIDE_PREVIEW_COMMENT, "|carousel_item", "comments_entry_point_teaser", "comments_entry_point_simplebox" ); addPathCallbacks( comments, previewComment ); } }
747
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ReturnYouTubeDislikeFilterPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/ReturnYouTubeDislikeFilterPatch.java
package app.revanced.integrations.youtube.patches.components; import androidx.annotation.GuardedBy; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import app.revanced.integrations.youtube.patches.ReturnYouTubeDislikePatch; import app.revanced.integrations.youtube.patches.VideoInformation; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.youtube.TrieSearch; /** * Searches for video id's in the proto buffer of Shorts dislike. * * Because multiple litho dislike spans are created in the background * (and also anytime litho refreshes the components, which is somewhat arbitrary), * that makes the value of {@link VideoInformation#getVideoId()} and {@link VideoInformation#getPlayerResponseVideoId()} * unreliable to determine which video id a Shorts litho span belongs to. * * But the correct video id does appear in the protobuffer just before a Shorts litho span is created. * * Once a way to asynchronously update litho text is found, this strategy will no longer be needed. */ public final class ReturnYouTubeDislikeFilterPatch extends Filter { /** * Last unique video id's loaded. Value is ignored and Map is treated as a Set. * Cannot use {@link LinkedHashSet} because it's missing #removeEldestEntry(). */ @GuardedBy("itself") private static final Map<String, Boolean> lastVideoIds = new LinkedHashMap<>() { /** * Number of video id's to keep track of for searching thru the buffer. * A minimum value of 3 should be sufficient, but check a few more just in case. */ private static final int NUMBER_OF_LAST_VIDEO_IDS_TO_TRACK = 5; @Override protected boolean removeEldestEntry(Entry eldest) { return size() > NUMBER_OF_LAST_VIDEO_IDS_TO_TRACK; } }; /** * Injection point. */ @SuppressWarnings("unused") public static void newPlayerResponseVideoId(String videoId, boolean isShortAndOpeningOrPlaying) { try { if (!isShortAndOpeningOrPlaying || !Settings.RYD_SHORTS.get()) { return; } synchronized (lastVideoIds) { if (lastVideoIds.put(videoId, Boolean.TRUE) == null) { Logger.printDebug(() -> "New Short video id: " + videoId); } } } catch (Exception ex) { Logger.printException(() -> "newPlayerResponseVideoId failure", ex); } } private final ByteArrayFilterGroupList videoIdFilterGroup = new ByteArrayFilterGroupList(); public ReturnYouTubeDislikeFilterPatch() { addPathCallbacks( new StringFilterGroup(Settings.RYD_SHORTS, "|shorts_dislike_button.eml|") ); // After the dislikes icon name is some binary data and then the video id for that specific short. videoIdFilterGroup.addAll( // Video was previously disliked before video was opened. new ByteArrayFilterGroup(null, "ic_right_dislike_on_shadowed"), // Video was not already disliked. new ByteArrayFilterGroup(null, "ic_right_dislike_off_shadowed") ); } @Override boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { FilterGroup.FilterGroupResult result = videoIdFilterGroup.check(protobufBufferArray); if (result.isFiltered()) { String matchedVideoId = findVideoId(protobufBufferArray); // Matched video will be null if in incognito mode. // Must pass a null id to correctly clear out the current video data. // Otherwise if a Short is opened in non-incognito, then incognito is enabled and another Short is opened, // the new incognito Short will show the old prior data. ReturnYouTubeDislikePatch.setLastLithoShortsVideoId(matchedVideoId); } return false; } @Nullable private String findVideoId(byte[] protobufBufferArray) { synchronized (lastVideoIds) { for (String videoId : lastVideoIds.keySet()) { if (byteArrayContainsString(protobufBufferArray, videoId)) { return videoId; } } return null; } } /** * This could use {@link TrieSearch}, but since the patterns are constantly changing * the overhead of updating the Trie might negate the search performance gain. */ private static boolean byteArrayContainsString(@NonNull byte[] array, @NonNull String text) { for (int i = 0, lastArrayStartIndex = array.length - text.length(); i <= lastArrayStartIndex; i++) { boolean found = true; for (int j = 0, textLength = text.length(); j < textLength; j++) { if (array[i + j] != (byte) text.charAt(j)) { found = false; break; } } if (found) { return true; } } return false; } }
5,359
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
LayoutComponentsFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/LayoutComponentsFilter.java
package app.revanced.integrations.youtube.patches.components; import static app.revanced.integrations.youtube.shared.NavigationBar.NavigationButton; import android.os.Build; import android.view.View; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.youtube.StringTrieSearch; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.youtube.shared.NavigationBar; import app.revanced.integrations.youtube.shared.PlayerType; @SuppressWarnings("unused") public final class LayoutComponentsFilter extends Filter { private final StringTrieSearch exceptions = new StringTrieSearch(); private static final StringTrieSearch mixPlaylistsExceptions = new StringTrieSearch(); private static final ByteArrayFilterGroup mixPlaylistsExceptions2 = new ByteArrayFilterGroup( null, "cell_description_body" ); private static final ByteArrayFilterGroup mixPlaylists = new ByteArrayFilterGroup( Settings.HIDE_MIX_PLAYLISTS, "&list=" ); private final StringFilterGroup searchResultShelfHeader; private final StringFilterGroup inFeedSurvey; private final StringFilterGroup notifyMe; private final StringFilterGroup expandableMetadata; private final ByteArrayFilterGroup searchResultRecommendations; private final StringFilterGroup searchResultVideo; private final StringFilterGroup compactChannelBarInner; private final StringFilterGroup compactChannelBarInnerButton; private final ByteArrayFilterGroup joinMembershipButton; private final StringFilterGroup horizontalShelves; static { mixPlaylistsExceptions.addPatterns( "V.ED", // Playlist browse id. "java.lang.ref.WeakReference" ); } @RequiresApi(api = Build.VERSION_CODES.N) public LayoutComponentsFilter() { exceptions.addPatterns( "home_video_with_context", "related_video_with_context", "search_video_with_context", "comment_thread", // Whitelist comments "|comment.", // Whitelist comment replies "library_recent_shelf" ); // Identifiers. final var graySeparator = new StringFilterGroup( Settings.HIDE_GRAY_SEPARATOR, "cell_divider" // layout residue (gray line above the buttoned ad), ); final var chipsShelf = new StringFilterGroup( Settings.HIDE_CHIPS_SHELF, "chips_shelf" ); addIdentifierCallbacks( graySeparator, chipsShelf ); // Paths. final var communityPosts = new StringFilterGroup( Settings.HIDE_COMMUNITY_POSTS, "post_base_wrapper", "image_post_root.eml" ); final var communityGuidelines = new StringFilterGroup( Settings.HIDE_COMMUNITY_GUIDELINES, "community_guidelines" ); final var subscribersCommunityGuidelines = new StringFilterGroup( Settings.HIDE_SUBSCRIBERS_COMMUNITY_GUIDELINES, "sponsorships_comments_upsell" ); final var channelMemberShelf = new StringFilterGroup( Settings.HIDE_CHANNEL_MEMBER_SHELF, "member_recognition_shelf" ); final var compactBanner = new StringFilterGroup( Settings.HIDE_COMPACT_BANNER, "compact_banner" ); inFeedSurvey = new StringFilterGroup( Settings.HIDE_FEED_SURVEY, "in_feed_survey", "slimline_survey" ); final var medicalPanel = new StringFilterGroup( Settings.HIDE_MEDICAL_PANELS, "medical_panel" ); final var paidPromotion = new StringFilterGroup( Settings.HIDE_PAID_PROMOTION_LABEL, "paid_content_overlay" ); final var infoPanel = new StringFilterGroup( Settings.HIDE_HIDE_INFO_PANELS, "publisher_transparency_panel", "single_item_information_panel" ); final var latestPosts = new StringFilterGroup( Settings.HIDE_HIDE_LATEST_POSTS, "post_shelf" ); final var channelGuidelines = new StringFilterGroup( Settings.HIDE_HIDE_CHANNEL_GUIDELINES, "channel_guidelines_entry_banner" ); final var emergencyBox = new StringFilterGroup( Settings.HIDE_EMERGENCY_BOX, "emergency_onebox" ); // The player audio track button does the exact same function as the audio track flyout menu option. // But if the copy url button is shown, these button clashes and the the audio button does not work. // Previously this was a setting to show/hide the player button. // But it was decided it's simpler to always hide this button because: // - it doesn't work with copy video url feature // - the button is rare // - always hiding makes the ReVanced settings simpler and easier to understand // - nobody is going to notice the redundant button is always hidden final var audioTrackButton = new StringFilterGroup( null, "multi_feed_icon_button" ); final var artistCard = new StringFilterGroup( Settings.HIDE_ARTIST_CARDS, "official_card" ); expandableMetadata = new StringFilterGroup( Settings.HIDE_EXPANDABLE_CHIP, "inline_expander" ); final var videoQualityMenuFooter = new StringFilterGroup( Settings.HIDE_VIDEO_QUALITY_MENU_FOOTER, "quality_sheet_footer" ); final var channelBar = new StringFilterGroup( Settings.HIDE_CHANNEL_BAR, "channel_bar" ); final var relatedVideos = new StringFilterGroup( Settings.HIDE_RELATED_VIDEOS, "fullscreen_related_videos" ); final var playables = new StringFilterGroup( Settings.HIDE_PLAYABLES, "horizontal_gaming_shelf.eml" ); final var quickActions = new StringFilterGroup( Settings.HIDE_QUICK_ACTIONS, "quick_actions" ); final var imageShelf = new StringFilterGroup( Settings.HIDE_IMAGE_SHELF, "image_shelf" ); final var timedReactions = new StringFilterGroup( Settings.HIDE_TIMED_REACTIONS, "emoji_control_panel", "timed_reaction" ); searchResultShelfHeader = new StringFilterGroup( Settings.HIDE_SEARCH_RESULT_SHELF_HEADER, "shelf_header.eml" ); notifyMe = new StringFilterGroup( Settings.HIDE_NOTIFY_ME_BUTTON, "set_reminder_button" ); compactChannelBarInner = new StringFilterGroup( Settings.HIDE_JOIN_MEMBERSHIP_BUTTON, "compact_channel_bar_inner" ); compactChannelBarInnerButton = new StringFilterGroup( null, "|button.eml|" ); joinMembershipButton = new ByteArrayFilterGroup( null, "sponsorships" ); final var channelWatermark = new StringFilterGroup( Settings.HIDE_VIDEO_CHANNEL_WATERMARK, "featured_channel_watermark_overlay" ); final var forYouShelf = new StringFilterGroup( Settings.HIDE_FOR_YOU_SHELF, "mixed_content_shelf" ); searchResultVideo = new StringFilterGroup( Settings.HIDE_SEARCH_RESULT_RECOMMENDATIONS, "search_video_with_context.eml" ); searchResultRecommendations = new ByteArrayFilterGroup( Settings.HIDE_SEARCH_RESULT_RECOMMENDATIONS, "endorsement_header_footer" ); horizontalShelves = new StringFilterGroup( Settings.HIDE_HORIZONTAL_SHELVES, "horizontal_video_shelf.eml", "horizontal_shelf.eml", "horizontal_tile_shelf.eml" ); addPathCallbacks( expandableMetadata, inFeedSurvey, notifyMe, channelBar, communityPosts, paidPromotion, searchResultVideo, latestPosts, channelWatermark, communityGuidelines, playables, quickActions, relatedVideos, compactBanner, compactChannelBarInner, medicalPanel, videoQualityMenuFooter, infoPanel, emergencyBox, subscribersCommunityGuidelines, channelGuidelines, audioTrackButton, artistCard, timedReactions, imageShelf, channelMemberShelf, forYouShelf, horizontalShelves ); } @Override boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { if (matchedGroup == searchResultVideo) { if (searchResultRecommendations.check(protobufBufferArray).isFiltered()) { return super.isFiltered(identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex); } return false; } // The groups are excluded from the filter due to the exceptions list below. // Filter them separately here. if (matchedGroup == notifyMe || matchedGroup == inFeedSurvey || matchedGroup == expandableMetadata) { return super.isFiltered(identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex); } if (exceptions.matches(path)) return false; // Exceptions are not filtered. if (matchedGroup == compactChannelBarInner) { if (compactChannelBarInnerButton.check(path).isFiltered()) { // The filter may be broad, but in the context of a compactChannelBarInnerButton, // it's safe to assume that the button is the only thing that should be hidden. if (joinMembershipButton.check(protobufBufferArray).isFiltered()) { return super.isFiltered(identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex); } } return false; } // TODO: This also hides the feed Shorts shelf header if (matchedGroup == searchResultShelfHeader && contentIndex != 0) return false; if (matchedGroup == horizontalShelves) { if (contentIndex == 0 && hideShelves()) { return super.isFiltered(path, identifier, protobufBufferArray, matchedGroup, contentType, contentIndex); } return false; } return super.isFiltered(identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex); } /** * Injection point. * Called from a different place then the other filters. */ public static boolean filterMixPlaylists(final Object conversionContext, @Nullable final byte[] bytes) { if (bytes == null) { Logger.printDebug(() -> "bytes is null"); return false; } // Prevent playlist items being hidden, if a mix playlist is present in it. if (mixPlaylistsExceptions.matches(conversionContext.toString())) return false; if (!mixPlaylists.check(bytes).isFiltered()) return false; // Prevent hiding the description of some videos accidentally. if (mixPlaylistsExceptions2.check(bytes).isFiltered()) return false; Logger.printDebug(() -> "Filtered mix playlist"); return true; } /** * Injection point. */ public static boolean showWatermark() { return !Settings.HIDE_VIDEO_CHANNEL_WATERMARK.get(); } private static final boolean HIDE_SHOW_MORE_BUTTON_ENABLED = Settings.HIDE_SHOW_MORE_BUTTON.get(); /** * Injection point. */ public static void hideShowMoreButton(View view) { if (HIDE_SHOW_MORE_BUTTON_ENABLED && NavigationBar.isSearchBarActive() // Search bar can be active but behind the player. && !PlayerType.getCurrent().isMaximizedOrFullscreen()) { Utils.hideViewByLayoutParams(view); } } private static boolean hideShelves() { // If the player is opened while library is selected, // then filter any recommendations below the player. if (PlayerType.getCurrent().isMaximizedOrFullscreen() // Or if the search is active while library is selected, then also filter. || NavigationBar.isSearchBarActive()) { return true; } // Check navigation button last. // Only filter if the library tab is not selected. // This check is important as the shelf layout is used for the library tab playlists. NavigationButton selectedNavButton = NavigationButton.getSelectedNavigationButton(); return selectedNavButton != null && !selectedNavButton.isLibraryOrYouTab(); } }
14,004
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
HideInfoCardsFilterPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/HideInfoCardsFilterPatch.java
package app.revanced.integrations.youtube.patches.components; import app.revanced.integrations.youtube.settings.Settings; @SuppressWarnings("unused") public final class HideInfoCardsFilterPatch extends Filter { public HideInfoCardsFilterPatch() { addIdentifierCallbacks( new StringFilterGroup( Settings.HIDE_INFO_CARDS, "info_card_teaser_overlay.eml" ) ); } }
467
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ButtonsFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/ButtonsFilter.java
package app.revanced.integrations.youtube.patches.components; import androidx.annotation.Nullable; import app.revanced.integrations.youtube.settings.Settings; @SuppressWarnings("unused") final class ButtonsFilter extends Filter { private static final String VIDEO_ACTION_BAR_PATH = "video_action_bar.eml"; private final StringFilterGroup actionBarGroup; private final StringFilterGroup bufferFilterPathGroup; private final ByteArrayFilterGroupList bufferButtonsGroupList = new ByteArrayFilterGroupList(); public ButtonsFilter() { actionBarGroup = new StringFilterGroup( null, VIDEO_ACTION_BAR_PATH ); addIdentifierCallbacks(actionBarGroup); bufferFilterPathGroup = new StringFilterGroup( null, "|CellType|CollectionType|CellType|ContainerType|button.eml|" ); addPathCallbacks( new StringFilterGroup( Settings.HIDE_LIKE_DISLIKE_BUTTON, "|segmented_like_dislike_button" ), new StringFilterGroup( Settings.HIDE_DOWNLOAD_BUTTON, "|download_button.eml|" ), new StringFilterGroup( Settings.HIDE_PLAYLIST_BUTTON, "|save_to_playlist_button" ), new StringFilterGroup( Settings.HIDE_CLIP_BUTTON, "|clip_button.eml|" ), bufferFilterPathGroup ); bufferButtonsGroupList.addAll( new ByteArrayFilterGroup( Settings.HIDE_REPORT_BUTTON, "yt_outline_flag" ), new ByteArrayFilterGroup( Settings.HIDE_SHARE_BUTTON, "yt_outline_share" ), new ByteArrayFilterGroup( Settings.HIDE_REMIX_BUTTON, "yt_outline_youtube_shorts_plus" ), // Check for clip button both here and using a path filter, // as there's a chance the path is a generic action button and won't contain 'clip_button' new ByteArrayFilterGroup( Settings.HIDE_CLIP_BUTTON, "yt_outline_scissors" ), new ByteArrayFilterGroup( Settings.HIDE_SHOP_BUTTON, "yt_outline_bag" ), new ByteArrayFilterGroup( Settings.HIDE_THANKS_BUTTON, "yt_outline_dollar_sign_heart" ) ); } private boolean isEveryFilterGroupEnabled() { for (var group : pathCallbacks) if (!group.isEnabled()) return false; for (var group : bufferButtonsGroupList) if (!group.isEnabled()) return false; return true; } @Override boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { // If the current matched group is the action bar group, // in case every filter group is enabled, hide the action bar. if (matchedGroup == actionBarGroup) { if (!isEveryFilterGroupEnabled()) { return false; } } else if (matchedGroup == bufferFilterPathGroup) { // Make sure the current path is the right one // to avoid false positives. if (!path.startsWith(VIDEO_ACTION_BAR_PATH)) return false; // In case the group list has no match, return false. if (!bufferButtonsGroupList.check(protobufBufferArray).isFiltered()) return false; } return super.isFiltered(identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex); } }
4,101
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ShortsFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/ShortsFilter.java
package app.revanced.integrations.youtube.patches.components; import static app.revanced.integrations.shared.Utils.hideViewUnderCondition; import static app.revanced.integrations.youtube.shared.NavigationBar.NavigationButton; import android.view.View; import androidx.annotation.Nullable; import com.google.android.libraries.youtube.rendering.ui.pivotbar.PivotBar; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.youtube.shared.NavigationBar; import app.revanced.integrations.youtube.shared.PlayerType; @SuppressWarnings("unused") public final class ShortsFilter extends Filter { public static PivotBar pivotBar; // Set by patch. private final static String REEL_CHANNEL_BAR_PATH = "reel_channel_bar.eml"; /** * For paid promotion label and subscribe button that appears in the channel bar. */ private final static String REEL_METAPANEL_PATH = "reel_metapanel.eml"; private final StringFilterGroup shortsCompactFeedVideoPath; private final ByteArrayFilterGroup shortsCompactFeedVideoBuffer; private final StringFilterGroup subscribeButton; private final StringFilterGroup joinButton; private final StringFilterGroup paidPromotionButton; private final StringFilterGroup shelfHeader; private final StringFilterGroup suggestedAction; private final ByteArrayFilterGroupList suggestedActionsGroupList = new ByteArrayFilterGroupList(); private final StringFilterGroup actionBar; private final ByteArrayFilterGroupList videoActionButtonGroupList = new ByteArrayFilterGroupList(); public ShortsFilter() { // // Identifier components. // var shortsIdentifiers = new StringFilterGroup( null, // Setting is based on navigation state. "shorts_shelf", "inline_shorts", "shorts_grid", "shorts_video_cell", "shorts_pivot_item" ); // Feed Shorts shelf header. // Use a different filter group for this pattern, as it requires an additional check after matching. shelfHeader = new StringFilterGroup( null, "shelf_header.eml" ); addIdentifierCallbacks(shortsIdentifiers, shelfHeader); // // Path components. // // Shorts that appear in the feed/search when the device is using tablet layout. shortsCompactFeedVideoPath = new StringFilterGroup(null, "compact_video.eml"); // Filter out items that use the 'frame0' thumbnail. // This is a valid thumbnail for both regular videos and Shorts, // but it appears these thumbnails are used only for Shorts. shortsCompactFeedVideoBuffer = new ByteArrayFilterGroup(null, "/frame0.jpg"); // Shorts player components. StringFilterGroup pausedOverlayButtons = new StringFilterGroup( Settings.HIDE_SHORTS_PAUSED_OVERLAY_BUTTONS, "shorts_paused_state" ); StringFilterGroup channelBar = new StringFilterGroup( Settings.HIDE_SHORTS_CHANNEL_BAR, REEL_CHANNEL_BAR_PATH ); StringFilterGroup fullVideoLinkLabel = new StringFilterGroup( Settings.HIDE_SHORTS_FULL_VIDEO_LINK_LABEL, "reel_multi_format_link" ); StringFilterGroup videoTitle = new StringFilterGroup( Settings.HIDE_SHORTS_VIDEO_TITLE, "shorts_video_title_item" ); StringFilterGroup reelSoundMetadata = new StringFilterGroup( Settings.HIDE_SHORTS_SOUND_METADATA_LABEL, "reel_sound_metadata" ); StringFilterGroup soundButton = new StringFilterGroup( Settings.HIDE_SHORTS_SOUND_BUTTON, "reel_pivot_button" ); StringFilterGroup infoPanel = new StringFilterGroup( Settings.HIDE_SHORTS_INFO_PANEL, "shorts_info_panel_overview" ); joinButton = new StringFilterGroup( Settings.HIDE_SHORTS_JOIN_BUTTON, "sponsor_button" ); subscribeButton = new StringFilterGroup( Settings.HIDE_SHORTS_SUBSCRIBE_BUTTON, "subscribe_button" ); paidPromotionButton = new StringFilterGroup( Settings.HIDE_PAID_PROMOTION_LABEL, "reel_player_disclosure.eml" ); actionBar = new StringFilterGroup( null, "shorts_action_bar" ); suggestedAction = new StringFilterGroup( null, "suggested_action.eml" ); addPathCallbacks( shortsCompactFeedVideoPath, suggestedAction, actionBar, joinButton, subscribeButton, paidPromotionButton, pausedOverlayButtons, channelBar, fullVideoLinkLabel, videoTitle, reelSoundMetadata, soundButton, infoPanel ); // // Action buttons // videoActionButtonGroupList.addAll( // This also appears as the path item 'shorts_like_button.eml' new ByteArrayFilterGroup( Settings.HIDE_SHORTS_LIKE_BUTTON, "reel_like_button", "reel_like_toggled_button" ), // This also appears as the path item 'shorts_dislike_button.eml' new ByteArrayFilterGroup( Settings.HIDE_SHORTS_DISLIKE_BUTTON, "reel_dislike_button", "reel_dislike_toggled_button" ), new ByteArrayFilterGroup( Settings.HIDE_SHORTS_COMMENTS_BUTTON, "reel_comment_button" ), new ByteArrayFilterGroup( Settings.HIDE_SHORTS_SHARE_BUTTON, "reel_share_button" ), new ByteArrayFilterGroup( Settings.HIDE_SHORTS_REMIX_BUTTON, "reel_remix_button" ) ); // // Suggested actions. // suggestedActionsGroupList.addAll( new ByteArrayFilterGroup( Settings.HIDE_SHORTS_SHOP_BUTTON, "yt_outline_bag_" ), new ByteArrayFilterGroup( Settings.HIDE_SHORTS_TAGGED_PRODUCTS, // Product buttons show pictures of the products, and does not have any unique icons to identify. // Instead use a unique identifier found in the buffer. "PAproduct_listZ" ), new ByteArrayFilterGroup( Settings.HIDE_SHORTS_LOCATION_LABEL, "yt_outline_location_point_" ), new ByteArrayFilterGroup( Settings.HIDE_SHORTS_SAVE_SOUND_BUTTON, "yt_outline_list_add_" ), new ByteArrayFilterGroup( Settings.HIDE_SHORTS_SEARCH_SUGGESTIONS, "yt_outline_search_" ) ); } @Override boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { if (contentType == FilterContentType.PATH) { if (matchedGroup == subscribeButton || matchedGroup == joinButton || matchedGroup == paidPromotionButton) { // Selectively filter to avoid false positive filtering of other subscribe/join buttons. if (path.startsWith(REEL_CHANNEL_BAR_PATH) || path.startsWith(REEL_METAPANEL_PATH)) { return super.isFiltered( identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex ); } return false; } if (matchedGroup == shortsCompactFeedVideoPath) { if (shouldHideShortsFeedItems() && contentIndex == 0 && shortsCompactFeedVideoBuffer.check(protobufBufferArray).isFiltered()) { return super.isFiltered(identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex); } return false; } // Video action buttons (like, dislike, comment, share, remix) have the same path. if (matchedGroup == actionBar) { if (videoActionButtonGroupList.check(protobufBufferArray).isFiltered()) { return super.isFiltered( identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex ); } return false; } if (matchedGroup == suggestedAction) { // Suggested actions can be at the start or in the middle of a path. if (suggestedActionsGroupList.check(protobufBufferArray).isFiltered()) { return super.isFiltered( identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex ); } return false; } } else { // Feed/search identifier components. if (matchedGroup == shelfHeader) { // Because the header is used in watch history and possibly other places, check for the index, // which is 0 when the shelf header is used for Shorts. if (contentIndex != 0) return false; } if (!shouldHideShortsFeedItems()) return false; } // Super class handles logging. return super.isFiltered(identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex); } private static boolean shouldHideShortsFeedItems() { final boolean hideHome = Settings.HIDE_SHORTS_HOME.get(); final boolean hideSubscriptions = Settings.HIDE_SHORTS_SUBSCRIPTIONS.get(); final boolean hideSearch = Settings.HIDE_SHORTS_SEARCH.get(); if (hideHome && hideSubscriptions && hideSearch) { // Shorts suggestions can load in the background if a video is opened and // then immediately minimized before any suggestions are loaded. // In this state the player type will show minimized, which makes it not possible to // distinguish between Shorts suggestions loading in the player and between // scrolling thru search/home/subscription tabs while a player is minimized. // // To avoid this situation for users that never want to show Shorts (all hide Shorts options are enabled) // then hide all Shorts everywhere including the Library history and Library playlists. return true; } // Must check player type first, as search bar can be active behind the player. if (PlayerType.getCurrent().isMaximizedOrFullscreen()) { // For now, consider the under video results the same as the home feed. return hideHome; } // Must check second, as search can be from any tab. if (NavigationBar.isSearchBarActive()) { return hideSearch; } // Avoid checking navigation button status if all other Shorts should show. if (!hideHome && !hideSubscriptions) { return false; } NavigationButton selectedNavButton = NavigationButton.getSelectedNavigationButton(); if (selectedNavButton == null) { return hideHome; // Unknown tab, treat the same as home. } if (selectedNavButton == NavigationButton.HOME) { return hideHome; } if (selectedNavButton == NavigationButton.SUBSCRIPTIONS) { return hideSubscriptions; } // User must be in the library tab. Don't hide the history or any playlists here. return false; } public static void hideShortsShelf(final View shortsShelfView) { if (shouldHideShortsFeedItems()) { Utils.hideViewByLayoutParams(shortsShelfView); } } // region Hide the buttons in older versions of YouTube. New versions use Litho. public static void hideShortsCommentsButton(final View commentsButtonView) { hideViewUnderCondition(Settings.HIDE_SHORTS_COMMENTS_BUTTON, commentsButtonView); } public static void hideShortsRemixButton(final View remixButtonView) { hideViewUnderCondition(Settings.HIDE_SHORTS_REMIX_BUTTON, remixButtonView); } public static void hideShortsShareButton(final View shareButtonView) { hideViewUnderCondition(Settings.HIDE_SHORTS_SHARE_BUTTON, shareButtonView); } // endregion public static void hideNavigationBar() { if (!Settings.HIDE_SHORTS_NAVIGATION_BAR.get()) return; if (pivotBar == null) return; pivotBar.setVisibility(View.GONE); } public static View hideNavigationBar(final View navigationBarView) { if (Settings.HIDE_SHORTS_NAVIGATION_BAR.get()) return null; // Hides the navigation bar. return navigationBarView; } }
13,635
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
LithoFilterPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/LithoFilterPatch.java
package app.revanced.integrations.youtube.patches.components; import android.os.Build; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Spliterator; import java.util.function.Consumer; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.settings.BooleanSetting; import app.revanced.integrations.shared.settings.BaseSettings; import app.revanced.integrations.youtube.ByteTrieSearch; import app.revanced.integrations.youtube.StringTrieSearch; import app.revanced.integrations.youtube.TrieSearch; import app.revanced.integrations.youtube.settings.Settings; abstract class FilterGroup<T> { final static class FilterGroupResult { private BooleanSetting setting; private int matchedIndex; private int matchedLength; // In the future it might be useful to include which pattern matched, // but for now that is not needed. FilterGroupResult() { this(null, -1, 0); } FilterGroupResult(BooleanSetting setting, int matchedIndex, int matchedLength) { setValues(setting, matchedIndex, matchedLength); } public void setValues(BooleanSetting setting, int matchedIndex, int matchedLength) { this.setting = setting; this.matchedIndex = matchedIndex; this.matchedLength = matchedLength; } /** * A null value if the group has no setting, * or if no match is returned from {@link FilterGroupList#check(Object)}. */ public BooleanSetting getSetting() { return setting; } public boolean isFiltered() { return matchedIndex >= 0; } /** * Matched index of first pattern that matched, or -1 if nothing matched. */ public int getMatchedIndex() { return matchedIndex; } /** * Length of the matched filter pattern. */ public int getMatchedLength() { return matchedLength; } } protected final BooleanSetting setting; protected final T[] filters; /** * Initialize a new filter group. * * @param setting The associated setting. * @param filters The filters. */ @SafeVarargs public FilterGroup(final BooleanSetting setting, final T... filters) { this.setting = setting; this.filters = filters; if (filters.length == 0) { throw new IllegalArgumentException("Must use one or more filter patterns (zero specified)"); } } public boolean isEnabled() { return setting == null || setting.get(); } /** * @return If {@link FilterGroupList} should include this group when searching. * By default, all filters are included except non enabled settings that require reboot. */ public boolean includeInSearch() { return isEnabled() || !setting.rebootApp; } @NonNull @Override public String toString() { return getClass().getSimpleName() + ": " + (setting == null ? "(null setting)" : setting); } public abstract FilterGroupResult check(final T stack); } class StringFilterGroup extends FilterGroup<String> { public StringFilterGroup(final BooleanSetting setting, final String... filters) { super(setting, filters); } @Override public FilterGroupResult check(final String string) { int matchedIndex = -1; int matchedLength = 0; if (isEnabled()) { for (String pattern : filters) { if (!string.isEmpty()) { final int indexOf = string.indexOf(pattern); if (indexOf >= 0) { matchedIndex = indexOf; matchedLength = pattern.length(); break; } } } } return new FilterGroupResult(setting, matchedIndex, matchedLength); } } /** * If you have more than 1 filter patterns, then all instances of * this class should filtered using {@link ByteArrayFilterGroupList#check(byte[])}, * which uses a prefix tree to give better performance. */ class ByteArrayFilterGroup extends FilterGroup<byte[]> { private volatile int[][] failurePatterns; // Modified implementation from https://stackoverflow.com/a/1507813 private static int indexOf(final byte[] data, final byte[] pattern, final int[] failure) { // Finds the first occurrence of the pattern in the byte array using // KMP matching algorithm. int patternLength = pattern.length; for (int i = 0, j = 0, dataLength = data.length; i < dataLength; i++) { while (j > 0 && pattern[j] != data[i]) { j = failure[j - 1]; } if (pattern[j] == data[i]) { j++; } if (j == patternLength) { return i - patternLength + 1; } } return -1; } private static int[] createFailurePattern(byte[] pattern) { // Computes the failure function using a boot-strapping process, // where the pattern is matched against itself. final int patternLength = pattern.length; final int[] failure = new int[patternLength]; for (int i = 1, j = 0; i < patternLength; i++) { while (j > 0 && pattern[j] != pattern[i]) { j = failure[j - 1]; } if (pattern[j] == pattern[i]) { j++; } failure[i] = j; } return failure; } public ByteArrayFilterGroup(BooleanSetting setting, byte[]... filters) { super(setting, filters); } /** * Converts the Strings into byte arrays. Used to search for text in binary data. */ public ByteArrayFilterGroup(BooleanSetting setting, String... filters) { super(setting, ByteTrieSearch.convertStringsToBytes(filters)); } private synchronized void buildFailurePatterns() { if (failurePatterns != null) return; // Thread race and another thread already initialized the search. Logger.printDebug(() -> "Building failure array for: " + this); int[][] failurePatterns = new int[filters.length][]; int i = 0; for (byte[] pattern : filters) { failurePatterns[i++] = createFailurePattern(pattern); } this.failurePatterns = failurePatterns; // Must set after initialization finishes. } @Override public FilterGroupResult check(final byte[] bytes) { int matchedLength = 0; int matchedIndex = -1; if (isEnabled()) { int[][] failures = failurePatterns; if (failures == null) { buildFailurePatterns(); // Lazy load. failures = failurePatterns; } for (int i = 0, length = filters.length; i < length; i++) { byte[] filter = filters[i]; matchedIndex = indexOf(bytes, filter, failures[i]); if (matchedIndex >= 0) { matchedLength = filter.length; break; } } } return new FilterGroupResult(setting, matchedIndex, matchedLength); } } abstract class FilterGroupList<V, T extends FilterGroup<V>> implements Iterable<T> { private final List<T> filterGroups = new ArrayList<>(); private final TrieSearch<V> search = createSearchGraph(); @SafeVarargs protected final void addAll(final T... groups) { filterGroups.addAll(Arrays.asList(groups)); for (T group : groups) { if (!group.includeInSearch()) { continue; } for (V pattern : group.filters) { search.addPattern(pattern, (textSearched, matchedStartIndex, matchedLength, callbackParameter) -> { if (group.isEnabled()) { FilterGroup.FilterGroupResult result = (FilterGroup.FilterGroupResult) callbackParameter; result.setValues(group.setting, matchedStartIndex, matchedLength); return true; } return false; }); } } } @NonNull @Override public Iterator<T> iterator() { return filterGroups.iterator(); } @RequiresApi(api = Build.VERSION_CODES.N) @Override public void forEach(@NonNull Consumer<? super T> action) { filterGroups.forEach(action); } @RequiresApi(api = Build.VERSION_CODES.N) @NonNull @Override public Spliterator<T> spliterator() { return filterGroups.spliterator(); } protected FilterGroup.FilterGroupResult check(V stack) { FilterGroup.FilterGroupResult result = new FilterGroup.FilterGroupResult(); search.matches(stack, result); return result; } protected abstract TrieSearch<V> createSearchGraph(); } final class StringFilterGroupList extends FilterGroupList<String, StringFilterGroup> { protected StringTrieSearch createSearchGraph() { return new StringTrieSearch(); } } /** * If searching for a single byte pattern, then it is slightly better to use * {@link ByteArrayFilterGroup#check(byte[])} as it uses KMP which is faster * than a prefix tree to search for only 1 pattern. */ final class ByteArrayFilterGroupList extends FilterGroupList<byte[], ByteArrayFilterGroup> { protected ByteTrieSearch createSearchGraph() { return new ByteTrieSearch(); } } /** * Filters litho based components. * * Callbacks to filter content are added using {@link #addIdentifierCallbacks(StringFilterGroup...)} * and {@link #addPathCallbacks(StringFilterGroup...)}. * * To filter {@link FilterContentType#PROTOBUFFER}, first add a callback to * either an identifier or a path. * Then inside {@link #isFiltered(String, String, byte[], StringFilterGroup, FilterContentType, int)} * search for the buffer content using either a {@link ByteArrayFilterGroup} (if searching for 1 pattern) * or a {@link ByteArrayFilterGroupList} (if searching for more than 1 pattern). * * All callbacks must be registered before the constructor completes. */ abstract class Filter { public enum FilterContentType { IDENTIFIER, PATH, PROTOBUFFER } /** * Identifier callbacks. Do not add to this instance, * and instead use {@link #addIdentifierCallbacks(StringFilterGroup...)}. */ protected final List<StringFilterGroup> identifierCallbacks = new ArrayList<>(); /** * Path callbacks. Do not add to this instance, * and instead use {@link #addPathCallbacks(StringFilterGroup...)}. */ protected final List<StringFilterGroup> pathCallbacks = new ArrayList<>(); /** * Adds callbacks to {@link #isFiltered(String, String, byte[], StringFilterGroup, FilterContentType, int)} * if any of the groups are found. */ protected final void addIdentifierCallbacks(StringFilterGroup... groups) { identifierCallbacks.addAll(Arrays.asList(groups)); } /** * Adds callbacks to {@link #isFiltered(String, String, byte[], StringFilterGroup, FilterContentType, int)} * if any of the groups are found. */ protected final void addPathCallbacks(StringFilterGroup... groups) { pathCallbacks.addAll(Arrays.asList(groups)); } /** * Called after an enabled filter has been matched. * Default implementation is to always filter the matched component and log the action. * Subclasses can perform additional or different checks if needed. * <p> * If the content is to be filtered, subclasses should always * call this method (and never return a plain 'true'). * That way the logs will always show when a component was filtered and which filter hide it. * <p> * Method is called off the main thread. * * @param matchedGroup The actual filter that matched. * @param contentType The type of content matched. * @param contentIndex Matched index of the identifier or path. * @return True if the litho component should be filtered out. */ boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { if (BaseSettings.DEBUG.get()) { String filterSimpleName = getClass().getSimpleName(); if (contentType == FilterContentType.IDENTIFIER) { Logger.printDebug(() -> filterSimpleName + " Filtered identifier: " + identifier); } else { Logger.printDebug(() -> filterSimpleName + " Filtered path: " + path); } } return true; } } /** * Placeholder for actual filters. */ final class DummyFilter extends Filter { } @SuppressWarnings("unused") public final class LithoFilterPatch { /** * Simple wrapper to pass the litho parameters through the prefix search. */ private static final class LithoFilterParameters { @Nullable final String identifier; final String path; final byte[] protoBuffer; LithoFilterParameters(@Nullable String lithoIdentifier, String lithoPath, byte[] protoBuffer) { this.identifier = lithoIdentifier; this.path = lithoPath; this.protoBuffer = protoBuffer; } @NonNull @Override public String toString() { // Estimate the percentage of the buffer that are Strings. StringBuilder builder = new StringBuilder(Math.max(100, protoBuffer.length / 2)); builder.append( "ID: "); builder.append(identifier); builder.append(" Path: "); builder.append(path); if (Settings.DEBUG_PROTOBUFFER.get()) { builder.append(" BufferStrings: "); findAsciiStrings(builder, protoBuffer); } return builder.toString(); } /** * Search through a byte array for all ASCII strings. */ private static void findAsciiStrings(StringBuilder builder, byte[] buffer) { // Valid ASCII values (ignore control characters). final int minimumAscii = 32; // 32 = space character final int maximumAscii = 126; // 127 = delete character final int minimumAsciiStringLength = 4; // Minimum length of an ASCII string to include. String delimitingCharacter = "❙"; // Non ascii character, to allow easier log filtering. final int length = buffer.length; int start = 0; int end = 0; while (end < length) { int value = buffer[end]; if (value < minimumAscii || value > maximumAscii || end == length - 1) { if (end - start >= minimumAsciiStringLength) { for (int i = start; i < end; i++) { builder.append((char) buffer[i]); } builder.append(delimitingCharacter); } start = end + 1; } end++; } } } private static final Filter[] filters = new Filter[] { new DummyFilter() // Replaced by patch. }; private static final StringTrieSearch pathSearchTree = new StringTrieSearch(); private static final StringTrieSearch identifierSearchTree = new StringTrieSearch(); private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** * Because litho filtering is multi-threaded and the buffer is passed in from a different injection point, * the buffer is saved to a ThreadLocal so each calling thread does not interfere with other threads. */ private static final ThreadLocal<ByteBuffer> bufferThreadLocal = new ThreadLocal<>(); static { for (Filter filter : filters) { filterUsingCallbacks(identifierSearchTree, filter, filter.identifierCallbacks, Filter.FilterContentType.IDENTIFIER); filterUsingCallbacks(pathSearchTree, filter, filter.pathCallbacks, Filter.FilterContentType.PATH); } Logger.printDebug(() -> "Using: " + identifierSearchTree.numberOfPatterns() + " identifier filters" + " (" + identifierSearchTree.getEstimatedMemorySize() + " KB), " + pathSearchTree.numberOfPatterns() + " path filters" + " (" + pathSearchTree.getEstimatedMemorySize() + " KB)"); } private static void filterUsingCallbacks(StringTrieSearch pathSearchTree, Filter filter, List<StringFilterGroup> groups, Filter.FilterContentType type) { for (StringFilterGroup group : groups) { if (!group.includeInSearch()) { continue; } for (String pattern : group.filters) { pathSearchTree.addPattern(pattern, (textSearched, matchedStartIndex, matchedLength, callbackParameter) -> { if (!group.isEnabled()) return false; LithoFilterParameters parameters = (LithoFilterParameters) callbackParameter; return filter.isFiltered(parameters.identifier, parameters.path, parameters.protoBuffer, group, type, matchedStartIndex); } ); } } } /** * Injection point. Called off the main thread. */ @SuppressWarnings("unused") public static void setProtoBuffer(@Nullable ByteBuffer protobufBuffer) { // Set the buffer to a thread local. The buffer will remain in memory, even after the call to #filter completes. // This is intentional, as it appears the buffer can be set once and then filtered multiple times. // The buffer will be cleared from memory after a new buffer is set by the same thread, // or when the calling thread eventually dies. if (protobufBuffer == null) { // It appears the buffer can be cleared out just before the call to #filter() // Ignore this null value and retain the last buffer that was set. Logger.printDebug(() -> "Ignoring null protobuffer"); } else { bufferThreadLocal.set(protobufBuffer); } } /** * Injection point. Called off the main thread, and commonly called by multiple threads at the same time. */ @SuppressWarnings("unused") public static boolean filter(@Nullable String lithoIdentifier, @NonNull StringBuilder pathBuilder) { try { // It is assumed that protobufBuffer is empty as well in this case. if (pathBuilder.length() == 0) return false; ByteBuffer protobufBuffer = bufferThreadLocal.get(); final byte[] bufferArray; // Potentially the buffer may have been null or never set up until now. // Use an empty buffer so the litho id/path filters still work correctly. if (protobufBuffer == null) { Logger.printDebug(() -> "Proto buffer is null, using an empty buffer array"); bufferArray = EMPTY_BYTE_ARRAY; } else if (!protobufBuffer.hasArray()) { Logger.printDebug(() -> "Proto buffer does not have an array, using an empty buffer array"); bufferArray = EMPTY_BYTE_ARRAY; } else { bufferArray = protobufBuffer.array(); } LithoFilterParameters parameter = new LithoFilterParameters(lithoIdentifier, pathBuilder.toString(), bufferArray); Logger.printDebug(() -> "Searching " + parameter); if (parameter.identifier != null) { if (identifierSearchTree.matches(parameter.identifier, parameter)) return true; } if (pathSearchTree.matches(parameter.path, parameter)) return true; } catch (Exception ex) { Logger.printException(() -> "Litho filter failure", ex); } return false; } }
20,735
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
DescriptionComponentsFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/DescriptionComponentsFilter.java
package app.revanced.integrations.youtube.patches.components; import androidx.annotation.Nullable; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.youtube.StringTrieSearch; @SuppressWarnings("unused") final class DescriptionComponentsFilter extends Filter { private final StringTrieSearch exceptions = new StringTrieSearch(); public DescriptionComponentsFilter() { exceptions.addPatterns( "compact_channel", "description", "grid_video", "inline_expander", "metadata" ); final StringFilterGroup chapterSection = new StringFilterGroup( Settings.HIDE_CHAPTERS, "macro_markers_carousel" ); final StringFilterGroup infoCardsSection = new StringFilterGroup( Settings.HIDE_INFO_CARDS_SECTION, "infocards_section" ); final StringFilterGroup gameSection = new StringFilterGroup( Settings.HIDE_GAME_SECTION, "gaming_section" ); final StringFilterGroup musicSection = new StringFilterGroup( Settings.HIDE_MUSIC_SECTION, "music_section", "video_attributes_section" ); final StringFilterGroup podcastSection = new StringFilterGroup( Settings.HIDE_PODCAST_SECTION, "playlist_section" ); final StringFilterGroup transcriptSection = new StringFilterGroup( Settings.HIDE_TRANSCIPT_SECTION, "transcript_section" ); addPathCallbacks( chapterSection, infoCardsSection, gameSection, musicSection, podcastSection, transcriptSection ); } @Override boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { if (exceptions.matches(path)) return false; return super.isFiltered(path, identifier, protobufBufferArray, matchedGroup, contentType, contentIndex); } }
2,283
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
PlaybackSpeedMenuFilterPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/PlaybackSpeedMenuFilterPatch.java
package app.revanced.integrations.youtube.patches.components; import androidx.annotation.Nullable; import app.revanced.integrations.youtube.patches.playback.speed.CustomPlaybackSpeedPatch; /** * Abuse LithoFilter for {@link CustomPlaybackSpeedPatch}. */ public final class PlaybackSpeedMenuFilterPatch extends Filter { // Must be volatile or synchronized, as litho filtering runs off main thread and this field is then access from the main thread. public static volatile boolean isPlaybackSpeedMenuVisible; public PlaybackSpeedMenuFilterPatch() { addPathCallbacks(new StringFilterGroup( null, "playback_speed_sheet_content.eml-js" )); } @Override boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { isPlaybackSpeedMenuVisible = true; return false; } }
995
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
VideoQualityMenuFilterPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/VideoQualityMenuFilterPatch.java
package app.revanced.integrations.youtube.patches.components; import androidx.annotation.Nullable; import app.revanced.integrations.youtube.patches.playback.quality.RestoreOldVideoQualityMenuPatch; import app.revanced.integrations.youtube.settings.Settings; /** * Abuse LithoFilter for {@link RestoreOldVideoQualityMenuPatch}. */ public final class VideoQualityMenuFilterPatch extends Filter { // Must be volatile or synchronized, as litho filtering runs off main thread // and this field is then access from the main thread. public static volatile boolean isVideoQualityMenuVisible; public VideoQualityMenuFilterPatch() { addPathCallbacks(new StringFilterGroup( Settings.RESTORE_OLD_VIDEO_QUALITY_MENU, "quick_quality_sheet_content.eml-js" )); } @Override boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { isVideoQualityMenuVisible = true; return false; } }
1,108
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
KeywordContentFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/KeywordContentFilter.java
package app.revanced.integrations.youtube.patches.components; import static app.revanced.integrations.shared.StringRef.str; import static app.revanced.integrations.youtube.ByteTrieSearch.convertStringsToBytes; import static app.revanced.integrations.youtube.shared.NavigationBar.NavigationButton; import android.os.Build; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.youtube.ByteTrieSearch; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.youtube.shared.NavigationBar; import app.revanced.integrations.youtube.shared.PlayerType; /** * <pre> * Allows hiding home feed and search results based on keywords and/or channel names. * * Limitations: * - Searching for a keyword phrase will give no search results. * This is because the buffer for each video contains the text the user searched for, and everything * will be filtered away (even if that video title/channel does not contain any keywords). * - Filtering a channel name can still show Shorts from that channel in the search results. * The most common Shorts layouts do not include the channel name, so they will not be filtered. * - Some layout component residue will remain, such as the video chapter previews for some search results. * These components do not include the video title or channel name, and they * appear outside the filtered components so they are not caught. * - Keywords are case sensitive, but some casing variation is manually added. * (ie: "mr beast" automatically filters "Mr Beast" and "MR BEAST"). * - Keywords present in the layout or video data cannot be used as filters, otherwise all videos * will always be hidden. This patch checks for some words of these words. */ @SuppressWarnings("unused") @RequiresApi(api = Build.VERSION_CODES.N) final class KeywordContentFilter extends Filter { /** * Minimum keyword/phrase length to prevent excessively broad content filtering. */ private static final int MINIMUM_KEYWORD_LENGTH = 3; /** * Strings found in the buffer for every videos. * Full strings should be specified, as they are compared using {@link String#contains(CharSequence)}. * * This list does not include every common buffer string, and this can be added/changed as needed. * Words must be entered with the exact casing as found in the buffer. */ private static final String[] STRINGS_IN_EVERY_BUFFER = { // Video playback data. "https://i.ytimg.com/vi/", // Thumbnail url. "sddefault.jpg", // More video sizes exist, but for most devices only these 2 are used. "hqdefault.webp", "googlevideo.com/initplayback?source=youtube", // Video url. "ANDROID", // Video url parameter. // Video decoders. "OMX.ffmpeg.vp9.decoder", "OMX.Intel.sw_vd.vp9", "OMX.sprd.av1.decoder", "OMX.MTK.VIDEO.DECODER.SW.VP9", "c2.android.av1.decoder", "c2.mtk.sw.vp9.decoder", // User analytics. "https://ad.doubleclick.net/ddm/activity/", "DEVICE_ADVERTISER_ID_FOR_CONVERSION_TRACKING", // Litho components frequently found in the buffer that belong to the path filter items. "metadata.eml", "thumbnail.eml", "avatar.eml", "overflow_button.eml", }; /** * Substrings that are always first in the identifier. */ private final StringFilterGroup startsWithFilter = new StringFilterGroup( null, // Multiple settings are used and must be individually checked if active. "home_video_with_context.eml", "search_video_with_context.eml", "video_with_context.eml", // Subscription tab videos. "related_video_with_context.eml", "compact_video.eml", "inline_shorts", "shorts_video_cell", "shorts_pivot_item.eml" ); /** * Substrings that are never at the start of the path. */ private final StringFilterGroup containsFilter = new StringFilterGroup( null, "modern_type_shelf_header_content.eml", "shorts_lockup_cell.eml" // Part of 'shorts_shelf_carousel.eml' ); /** * The last value of {@link Settings#HIDE_KEYWORD_CONTENT_PHRASES} * parsed and loaded into {@link #bufferSearch}. * Allows changing the keywords without restarting the app. */ private volatile String lastKeywordPhrasesParsed; private volatile ByteTrieSearch bufferSearch; private static boolean hideKeywordSettingIsActive() { // Must check player type first, as search bar can be active behind the player. if (PlayerType.getCurrent().isMaximizedOrFullscreen()) { // For now, consider the under video results the same as the home feed. return Settings.HIDE_KEYWORD_CONTENT_HOME.get(); } // Must check second, as search can be from any tab. if (NavigationBar.isSearchBarActive()) { return Settings.HIDE_KEYWORD_CONTENT_SEARCH.get(); } // Avoid checking navigation button status if all other settings are off. final boolean hideHome = Settings.HIDE_KEYWORD_CONTENT_HOME.get(); final boolean hideSubscriptions = Settings.HIDE_KEYWORD_CONTENT_SUBSCRIPTIONS.get(); if (!hideHome && !hideSubscriptions) { return false; } NavigationButton selectedNavButton = NavigationButton.getSelectedNavigationButton(); if (selectedNavButton == null) { return hideHome; // Unknown tab, treat the same as home. } if (selectedNavButton == NavigationButton.HOME) { return hideHome; } if (selectedNavButton == NavigationButton.SUBSCRIPTIONS) { return hideSubscriptions; } // User is in the Library or Notifications tab. return false; } /** * Change first letter of the first word to use title case. */ private static String titleCaseFirstWordOnly(String sentence) { if (sentence.isEmpty()) { return sentence; } final int firstCodePoint = sentence.codePointAt(0); // In some non English languages title case is different than upper case. return new StringBuilder() .appendCodePoint(Character.toTitleCase(firstCodePoint)) .append(sentence, Character.charCount(firstCodePoint), sentence.length()) .toString(); } /** * Uppercase the first letter of each word. */ private static String capitalizeAllFirstLetters(String sentence) { if (sentence.isEmpty()) { return sentence; } final int delimiter = ' '; // Use code points and not characters to handle unicode surrogates. int[] codePoints = sentence.codePoints().toArray(); boolean capitalizeNext = true; for (int i = 0, length = codePoints.length; i < length; i++) { final int codePoint = codePoints[i]; if (codePoint == delimiter) { capitalizeNext = true; } else if (capitalizeNext) { codePoints[i] = Character.toUpperCase(codePoint); capitalizeNext = false; } } return new String(codePoints, 0, codePoints.length); } /** * @return If the phrase will will hide all videos. Not an exhaustive check. */ private static boolean phrasesWillHideAllVideos(@NonNull String[] phrases) { for (String commonString : STRINGS_IN_EVERY_BUFFER) { if (Utils.containsAny(commonString, phrases)) { return true; } } return false; } private synchronized void parseKeywords() { // Must be synchronized since Litho is multi-threaded. String rawKeywords = Settings.HIDE_KEYWORD_CONTENT_PHRASES.get(); //noinspection StringEquality if (rawKeywords == lastKeywordPhrasesParsed) { Logger.printDebug(() -> "Using previously initialized search"); return; // Another thread won the race, and search is already initialized. } ByteTrieSearch search = new ByteTrieSearch(); String[] split = rawKeywords.split("\n"); if (split.length != 0) { // Linked Set so log statement are more organized and easier to read. Set<String> keywords = new LinkedHashSet<>(10 * split.length); for (String phrase : split) { // Remove any trailing white space the user may have accidentally included. phrase = phrase.stripTrailing(); if (phrase.isBlank()) continue; if (phrase.length() < MINIMUM_KEYWORD_LENGTH) { // Do not reset the setting. Keep the invalid keywords so the user can fix the mistake. Utils.showToastLong(str("revanced_hide_keyword_toast_invalid_length", phrase, MINIMUM_KEYWORD_LENGTH)); continue; } // Add common casing that might appear. // // This could be simplified by adding case insensitive search to the prefix search, // which is very simple to add to StringTreSearch for Unicode and ByteTrieSearch for ASCII. // // But to support Unicode with ByteTrieSearch would require major changes because // UTF-8 characters can be different byte lengths, which does // not allow comparing two different byte arrays using simple plain array indexes. // // Instead add all common case variations of the words. String[] phraseVariations = { phrase, phrase.toLowerCase(), titleCaseFirstWordOnly(phrase), capitalizeAllFirstLetters(phrase), phrase.toUpperCase() }; if (phrasesWillHideAllVideos(phraseVariations)) { Utils.showToastLong(str("revanced_hide_keyword_toast_invalid_common", phrase)); continue; } keywords.addAll(Arrays.asList(phraseVariations)); } search.addPatterns(convertStringsToBytes(keywords.toArray(new String[0]))); Logger.printDebug(() -> "Search using: (" + search.getEstimatedMemorySize() + " KB) keywords: " + keywords); } bufferSearch = search; lastKeywordPhrasesParsed = rawKeywords; // Must set last. } public KeywordContentFilter() { // Keywords are parsed on first call to isFiltered() addPathCallbacks(startsWithFilter, containsFilter); } @Override boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { if (contentIndex != 0 && matchedGroup == startsWithFilter) { return false; } if (!hideKeywordSettingIsActive()) return false; // Field is intentionally compared using reference equality. //noinspection StringEquality if (Settings.HIDE_KEYWORD_CONTENT_PHRASES.get() != lastKeywordPhrasesParsed) { // User changed the keywords. parseKeywords(); } if (!bufferSearch.matches(protobufBufferArray)) { return false; } return super.isFiltered(identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex); } }
12,061
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
PlayerFlyoutMenuItemsFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/patches/components/PlayerFlyoutMenuItemsFilter.java
package app.revanced.integrations.youtube.patches.components; import android.os.Build; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.youtube.shared.PlayerType; @SuppressWarnings("unused") public class PlayerFlyoutMenuItemsFilter extends Filter { private final ByteArrayFilterGroupList flyoutFilterGroupList = new ByteArrayFilterGroupList(); private final ByteArrayFilterGroup exception; @RequiresApi(api = Build.VERSION_CODES.N) public PlayerFlyoutMenuItemsFilter() { exception = new ByteArrayFilterGroup( // Whitelist Quality menu item when "Hide Additional settings menu" is enabled Settings.HIDE_ADDITIONAL_SETTINGS_MENU, "quality_sheet" ); // Using pathFilterGroupList due to new flyout panel(A/B) addPathCallbacks( new StringFilterGroup(null, "overflow_menu_item.eml|") ); flyoutFilterGroupList.addAll( new ByteArrayFilterGroup( Settings.HIDE_CAPTIONS_MENU, "closed_caption" ), new ByteArrayFilterGroup( Settings.HIDE_ADDITIONAL_SETTINGS_MENU, "yt_outline_gear" ), new ByteArrayFilterGroup( Settings.HIDE_LOOP_VIDEO_MENU, "yt_outline_arrow_repeat_1_" ), new ByteArrayFilterGroup( Settings.HIDE_AMBIENT_MODE_MENU, "yt_outline_screen_light" ), new ByteArrayFilterGroup( Settings.HIDE_REPORT_MENU, "yt_outline_flag" ), new ByteArrayFilterGroup( Settings.HIDE_HELP_MENU, "yt_outline_question_circle" ), new ByteArrayFilterGroup( Settings.HIDE_MORE_INFO_MENU, "yt_outline_info_circle" ), new ByteArrayFilterGroup( Settings.HIDE_LOCK_SCREEN_MENU, "yt_outline_lock" ), new ByteArrayFilterGroup( Settings.HIDE_SPEED_MENU, "yt_outline_play_arrow_half_circle" ), new ByteArrayFilterGroup( Settings.HIDE_AUDIO_TRACK_MENU, "yt_outline_person_radar" ), new ByteArrayFilterGroup( Settings.HIDE_WATCH_IN_VR_MENU, "yt_outline_vr" ) ); } @Override boolean isFiltered(@Nullable String identifier, String path, byte[] protobufBufferArray, StringFilterGroup matchedGroup, FilterContentType contentType, int contentIndex) { // Only 1 path callback was added, so the matched group must be the overflow menu. if (contentIndex != 0) { return false; // Overflow menu is always the start of the path. } // Shorts also use this player flyout panel if (PlayerType.getCurrent().isNoneOrHidden() || exception.check(protobufBufferArray).isFiltered()) { return false; } if (flyoutFilterGroupList.check(protobufBufferArray).isFiltered()) { // Super class handles logging. return super.isFiltered(identifier, path, protobufBufferArray, matchedGroup, contentType, contentIndex); } return false; } }
3,781
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
Settings.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/settings/Settings.java
package app.revanced.integrations.youtube.settings; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.settings.*; import app.revanced.integrations.shared.settings.preference.SharedPrefCategory; import app.revanced.integrations.youtube.patches.AlternativeThumbnailsPatch.DeArrowAvailability; import app.revanced.integrations.youtube.patches.AlternativeThumbnailsPatch.StillImagesAvailability; import app.revanced.integrations.youtube.patches.AlternativeThumbnailsPatch.ThumbnailOption; import app.revanced.integrations.youtube.patches.AlternativeThumbnailsPatch.ThumbnailStillTime; import app.revanced.integrations.youtube.patches.spoof.SpoofAppVersionPatch; import app.revanced.integrations.youtube.sponsorblock.SponsorBlockSettings; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import static app.revanced.integrations.shared.settings.Setting.*; import static app.revanced.integrations.youtube.sponsorblock.objects.CategoryBehaviour.*; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; public class Settings extends BaseSettings { // External downloader public static final BooleanSetting EXTERNAL_DOWNLOADER = new BooleanSetting("revanced_external_downloader", FALSE); public static final BooleanSetting EXTERNAL_DOWNLOADER_ACTION_BUTTON = new BooleanSetting("revanced_external_downloader_action_button", FALSE); public static final StringSetting EXTERNAL_DOWNLOADER_PACKAGE_NAME = new StringSetting("revanced_external_downloader_name", "org.schabi.newpipe" /* NewPipe */, parentsAny(EXTERNAL_DOWNLOADER, EXTERNAL_DOWNLOADER_ACTION_BUTTON)); // Copy video URL public static final BooleanSetting COPY_VIDEO_URL = new BooleanSetting("revanced_copy_video_url", FALSE); public static final BooleanSetting COPY_VIDEO_URL_TIMESTAMP = new BooleanSetting("revanced_copy_video_url_timestamp", TRUE); // Video public static final BooleanSetting RESTORE_OLD_VIDEO_QUALITY_MENU = new BooleanSetting("revanced_restore_old_video_quality_menu", TRUE); public static final BooleanSetting REMEMBER_VIDEO_QUALITY_LAST_SELECTED = new BooleanSetting("revanced_remember_video_quality_last_selected", TRUE); public static final IntegerSetting VIDEO_QUALITY_DEFAULT_WIFI = new IntegerSetting("revanced_video_quality_default_wifi", -2); public static final IntegerSetting VIDEO_QUALITY_DEFAULT_MOBILE = new IntegerSetting("revanced_video_quality_default_mobile", -2); public static final BooleanSetting REMEMBER_PLAYBACK_SPEED_LAST_SELECTED = new BooleanSetting("revanced_remember_playback_speed_last_selected", TRUE); public static final FloatSetting PLAYBACK_SPEED_DEFAULT = new FloatSetting("revanced_playback_speed_default", 1.0f); public static final StringSetting CUSTOM_PLAYBACK_SPEEDS = new StringSetting("revanced_custom_playback_speeds", "0.25\n0.5\n0.75\n0.9\n0.95\n1.0\n1.05\n1.1\n1.25\n1.5\n1.75\n2.0\n3.0\n4.0\n5.0", true); @Deprecated // Patch is obsolete and no longer works with 19.09+ public static final BooleanSetting HDR_AUTO_BRIGHTNESS = new BooleanSetting("revanced_hdr_auto_brightness", TRUE); // Ads public static final BooleanSetting HIDE_FULLSCREEN_ADS = new BooleanSetting("revanced_hide_fullscreen_ads", TRUE); public static final BooleanSetting HIDE_BUTTONED_ADS = new BooleanSetting("revanced_hide_buttoned_ads", TRUE); public static final BooleanSetting HIDE_GENERAL_ADS = new BooleanSetting("revanced_hide_general_ads", TRUE); public static final BooleanSetting HIDE_GET_PREMIUM = new BooleanSetting("revanced_hide_get_premium", TRUE); public static final BooleanSetting HIDE_HIDE_LATEST_POSTS = new BooleanSetting("revanced_hide_latest_posts_ads", TRUE); public static final BooleanSetting HIDE_MERCHANDISE_BANNERS = new BooleanSetting("revanced_hide_merchandise_banners", TRUE); public static final BooleanSetting HIDE_PAID_PROMOTION_LABEL = new BooleanSetting("revanced_hide_paid_promotion_label", TRUE); public static final BooleanSetting HIDE_PRODUCTS_BANNER = new BooleanSetting("revanced_hide_products_banner", TRUE); public static final BooleanSetting HIDE_SHOPPING_LINKS = new BooleanSetting("revanced_hide_shopping_links", TRUE); public static final BooleanSetting HIDE_SELF_SPONSOR = new BooleanSetting("revanced_hide_self_sponsor_ads", TRUE); public static final BooleanSetting HIDE_VIDEO_ADS = new BooleanSetting("revanced_hide_video_ads", TRUE, true); public static final BooleanSetting HIDE_WEB_SEARCH_RESULTS = new BooleanSetting("revanced_hide_web_search_results", TRUE); // Layout public static final EnumSetting<ThumbnailOption> ALT_THUMBNAIL_HOME = new EnumSetting<>("revanced_alt_thumbnail_home", ThumbnailOption.ORIGINAL); public static final EnumSetting<ThumbnailOption> ALT_THUMBNAIL_SUBSCRIPTIONS = new EnumSetting<>("revanced_alt_thumbnail_subscription", ThumbnailOption.ORIGINAL); public static final EnumSetting<ThumbnailOption> ALT_THUMBNAIL_LIBRARY = new EnumSetting<>("revanced_alt_thumbnail_library", ThumbnailOption.ORIGINAL); public static final EnumSetting<ThumbnailOption> ALT_THUMBNAIL_PLAYER = new EnumSetting<>("revanced_alt_thumbnail_player", ThumbnailOption.ORIGINAL); public static final EnumSetting<ThumbnailOption> ALT_THUMBNAIL_SEARCH = new EnumSetting<>("revanced_alt_thumbnail_search", ThumbnailOption.ORIGINAL); public static final StringSetting ALT_THUMBNAIL_DEARROW_API_URL = new StringSetting("revanced_alt_thumbnail_dearrow_api_url", "https://dearrow-thumb.ajay.app/api/v1/getThumbnail", true, new DeArrowAvailability()); public static final BooleanSetting ALT_THUMBNAIL_DEARROW_CONNECTION_TOAST = new BooleanSetting("revanced_alt_thumbnail_dearrow_connection_toast", TRUE, new DeArrowAvailability()); public static final EnumSetting<ThumbnailStillTime> ALT_THUMBNAIL_STILLS_TIME = new EnumSetting<>("revanced_alt_thumbnail_stills_time", ThumbnailStillTime.MIDDLE, new StillImagesAvailability()); public static final BooleanSetting ALT_THUMBNAIL_STILLS_FAST = new BooleanSetting("revanced_alt_thumbnail_stills_fast", FALSE, new StillImagesAvailability()); public static final BooleanSetting CUSTOM_FILTER = new BooleanSetting("revanced_custom_filter", FALSE); public static final StringSetting CUSTOM_FILTER_STRINGS = new StringSetting("revanced_custom_filter_strings", "", true, parent(CUSTOM_FILTER)); public static final BooleanSetting DISABLE_FULLSCREEN_AMBIENT_MODE = new BooleanSetting("revanced_disable_fullscreen_ambient_mode", TRUE, true); public static final BooleanSetting DISABLE_RESUMING_SHORTS_PLAYER = new BooleanSetting("revanced_disable_resuming_shorts_player", FALSE); public static final BooleanSetting DISABLE_ROLLING_NUMBER_ANIMATIONS = new BooleanSetting("revanced_disable_rolling_number_animations", FALSE); public static final BooleanSetting DISABLE_SUGGESTED_VIDEO_END_SCREEN = new BooleanSetting("revanced_disable_suggested_video_end_screen", FALSE, true); public static final BooleanSetting GRADIENT_LOADING_SCREEN = new BooleanSetting("revanced_gradient_loading_screen", FALSE); public static final BooleanSetting HIDE_ALBUM_CARDS = new BooleanSetting("revanced_hide_album_cards", FALSE, true); public static final BooleanSetting HIDE_ARTIST_CARDS = new BooleanSetting("revanced_hide_artist_cards", FALSE); public static final BooleanSetting HIDE_AUTOPLAY_BUTTON = new BooleanSetting("revanced_hide_autoplay_button", TRUE, true); public static final BooleanSetting HIDE_HORIZONTAL_SHELVES = new BooleanSetting("revanced_hide_horizontal_shelves", TRUE); public static final BooleanSetting HIDE_CAPTIONS_BUTTON = new BooleanSetting("revanced_hide_captions_button", FALSE); public static final BooleanSetting HIDE_CAST_BUTTON = new BooleanSetting("revanced_hide_cast_button", TRUE, true); public static final BooleanSetting HIDE_CHANNEL_BAR = new BooleanSetting("revanced_hide_channel_bar", FALSE); public static final BooleanSetting HIDE_CHANNEL_MEMBER_SHELF = new BooleanSetting("revanced_hide_channel_member_shelf", TRUE); public static final BooleanSetting HIDE_CHIPS_SHELF = new BooleanSetting("revanced_hide_chips_shelf", TRUE); public static final BooleanSetting HIDE_COMMENTS_SECTION = new BooleanSetting("revanced_hide_comments_section", FALSE, true); public static final BooleanSetting HIDE_COMMUNITY_GUIDELINES = new BooleanSetting("revanced_hide_community_guidelines", TRUE); public static final BooleanSetting HIDE_COMMUNITY_POSTS = new BooleanSetting("revanced_hide_community_posts", FALSE); public static final BooleanSetting HIDE_COMPACT_BANNER = new BooleanSetting("revanced_hide_compact_banner", TRUE); public static final BooleanSetting HIDE_CROWDFUNDING_BOX = new BooleanSetting("revanced_hide_crowdfunding_box", FALSE, true); public static final BooleanSetting HIDE_EMAIL_ADDRESS = new BooleanSetting("revanced_hide_email_address", FALSE); public static final BooleanSetting HIDE_EMERGENCY_BOX = new BooleanSetting("revanced_hide_emergency_box", TRUE); public static final BooleanSetting HIDE_ENDSCREEN_CARDS = new BooleanSetting("revanced_hide_endscreen_cards", TRUE); public static final BooleanSetting HIDE_EXPANDABLE_CHIP = new BooleanSetting("revanced_hide_expandable_chip", TRUE); public static final BooleanSetting HIDE_FEED_SURVEY = new BooleanSetting("revanced_hide_feed_survey", TRUE); public static final BooleanSetting HIDE_FILTER_BAR_FEED_IN_FEED = new BooleanSetting("revanced_hide_filter_bar_feed_in_feed", FALSE, true); public static final BooleanSetting HIDE_FILTER_BAR_FEED_IN_RELATED_VIDEOS = new BooleanSetting("revanced_hide_filter_bar_feed_in_related_videos", FALSE, true); public static final BooleanSetting HIDE_FILTER_BAR_FEED_IN_SEARCH = new BooleanSetting("revanced_hide_filter_bar_feed_in_search", FALSE, true); public static final BooleanSetting HIDE_FLOATING_MICROPHONE_BUTTON = new BooleanSetting("revanced_hide_floating_microphone_button", TRUE, true); public static final BooleanSetting HIDE_FULLSCREEN_PANELS = new BooleanSetting("revanced_hide_fullscreen_panels", TRUE, true); public static final BooleanSetting HIDE_GRAY_SEPARATOR = new BooleanSetting("revanced_hide_gray_separator", TRUE); public static final BooleanSetting HIDE_HIDE_CHANNEL_GUIDELINES = new BooleanSetting("revanced_hide_channel_guidelines", TRUE); public static final BooleanSetting HIDE_HIDE_INFO_PANELS = new BooleanSetting("revanced_hide_info_panels", TRUE); public static final BooleanSetting HIDE_IMAGE_SHELF = new BooleanSetting("revanced_hide_image_shelf", TRUE); public static final BooleanSetting HIDE_INFO_CARDS = new BooleanSetting("revanced_hide_info_cards", TRUE); public static final BooleanSetting HIDE_JOIN_MEMBERSHIP_BUTTON = new BooleanSetting("revanced_hide_join_membership_button", TRUE); public static final BooleanSetting HIDE_KEYWORD_CONTENT_HOME = new BooleanSetting("revanced_hide_keyword_content_home", FALSE); public static final BooleanSetting HIDE_KEYWORD_CONTENT_SUBSCRIPTIONS = new BooleanSetting("revanced_hide_keyword_content_subscriptions", FALSE); public static final BooleanSetting HIDE_KEYWORD_CONTENT_SEARCH = new BooleanSetting("revanced_hide_keyword_content_search", FALSE); public static final StringSetting HIDE_KEYWORD_CONTENT_PHRASES = new StringSetting("revanced_hide_keyword_content_phrases", "", parentsAny(HIDE_KEYWORD_CONTENT_HOME, HIDE_KEYWORD_CONTENT_SUBSCRIPTIONS, HIDE_KEYWORD_CONTENT_SEARCH)); @Deprecated public static final BooleanSetting HIDE_LOAD_MORE_BUTTON = new BooleanSetting("revanced_hide_load_more_button", TRUE); public static final BooleanSetting HIDE_SHOW_MORE_BUTTON = new BooleanSetting("revanced_hide_show_more_button", TRUE, true); public static final BooleanSetting HIDE_MEDICAL_PANELS = new BooleanSetting("revanced_hide_medical_panels", TRUE); public static final BooleanSetting HIDE_MIX_PLAYLISTS = new BooleanSetting("revanced_hide_mix_playlists", TRUE); public static final BooleanSetting HIDE_MOVIES_SECTION = new BooleanSetting("revanced_hide_movies_section", TRUE); public static final BooleanSetting HIDE_NOTIFY_ME_BUTTON = new BooleanSetting("revanced_hide_notify_me_button", TRUE); public static final BooleanSetting HIDE_PLAYER_BUTTONS = new BooleanSetting("revanced_hide_player_buttons", FALSE); public static final BooleanSetting HIDE_PREVIEW_COMMENT = new BooleanSetting("revanced_hide_preview_comment", FALSE, true); public static final BooleanSetting HIDE_PLAYABLES = new BooleanSetting("revanced_hide_playables", TRUE); public static final BooleanSetting HIDE_QUICK_ACTIONS = new BooleanSetting("revanced_hide_quick_actions", FALSE); public static final BooleanSetting HIDE_RELATED_VIDEOS = new BooleanSetting("revanced_hide_related_videos", FALSE); public static final BooleanSetting HIDE_SEARCH_RESULT_SHELF_HEADER = new BooleanSetting("revanced_hide_search_result_shelf_header", FALSE); public static final BooleanSetting HIDE_SUBSCRIBERS_COMMUNITY_GUIDELINES = new BooleanSetting("revanced_hide_subscribers_community_guidelines", TRUE); public static final BooleanSetting HIDE_TIMED_REACTIONS = new BooleanSetting("revanced_hide_timed_reactions", TRUE); public static final BooleanSetting HIDE_TIMESTAMP = new BooleanSetting("revanced_hide_timestamp", FALSE); public static final BooleanSetting HIDE_VIDEO_CHANNEL_WATERMARK = new BooleanSetting("revanced_hide_channel_watermark", TRUE); public static final BooleanSetting HIDE_FOR_YOU_SHELF = new BooleanSetting("revanced_hide_for_you_shelf", TRUE); public static final BooleanSetting HIDE_VIDEO_QUALITY_MENU_FOOTER = new BooleanSetting("revanced_hide_video_quality_menu_footer", TRUE); public static final BooleanSetting HIDE_SEARCH_RESULT_RECOMMENDATIONS = new BooleanSetting("revanced_hide_search_result_recommendations", TRUE); public static final IntegerSetting PLAYER_OVERLAY_OPACITY = new IntegerSetting("revanced_player_overlay_opacity",100, true); public static final BooleanSetting PLAYER_POPUP_PANELS = new BooleanSetting("revanced_hide_player_popup_panels", FALSE); public static final BooleanSetting SPOOF_APP_VERSION = new BooleanSetting("revanced_spoof_app_version", FALSE, true, "revanced_spoof_app_version_user_dialog_message"); public static final StringSetting SPOOF_APP_VERSION_TARGET = new StringSetting("revanced_spoof_app_version_target", "17.33.42", true, parent(SPOOF_APP_VERSION)); public static final BooleanSetting TABLET_LAYOUT = new BooleanSetting("revanced_tablet_layout", FALSE, true, "revanced_tablet_layout_user_dialog_message"); public static final BooleanSetting USE_TABLET_MINIPLAYER = new BooleanSetting("revanced_tablet_miniplayer", FALSE, true); public static final BooleanSetting WIDE_SEARCHBAR = new BooleanSetting("revanced_wide_searchbar", FALSE, true); public static final StringSetting START_PAGE = new StringSetting("revanced_start_page", ""); // Navigation buttons public static final BooleanSetting HIDE_HOME_BUTTON = new BooleanSetting("revanced_hide_home_button", FALSE, true); public static final BooleanSetting HIDE_CREATE_BUTTON = new BooleanSetting("revanced_hide_create_button", TRUE, true); public static final BooleanSetting HIDE_SHORTS_BUTTON = new BooleanSetting("revanced_hide_shorts_button", TRUE, true); public static final BooleanSetting HIDE_SUBSCRIPTIONS_BUTTON = new BooleanSetting("revanced_hide_subscriptions_button", FALSE, true); public static final BooleanSetting SWITCH_CREATE_WITH_NOTIFICATIONS_BUTTON = new BooleanSetting("revanced_switch_create_with_notifications_button", TRUE, true); // Description public static final BooleanSetting HIDE_CHAPTERS = new BooleanSetting("revanced_hide_chapters", TRUE); public static final BooleanSetting HIDE_INFO_CARDS_SECTION = new BooleanSetting("revanced_hide_info_cards_section", TRUE); public static final BooleanSetting HIDE_GAME_SECTION = new BooleanSetting("revanced_hide_game_section", TRUE); public static final BooleanSetting HIDE_MUSIC_SECTION = new BooleanSetting("revanced_hide_music_section", TRUE); public static final BooleanSetting HIDE_PODCAST_SECTION = new BooleanSetting("revanced_hide_podcast_section", TRUE); public static final BooleanSetting HIDE_TRANSCIPT_SECTION = new BooleanSetting("revanced_hide_transcript_section", TRUE); // Shorts @Deprecated public static final BooleanSetting DEPRECATED_HIDE_SHORTS = new BooleanSetting("revanced_hide_shorts", FALSE); public static final BooleanSetting HIDE_SHORTS_HOME = new BooleanSetting("revanced_hide_shorts_home", FALSE); public static final BooleanSetting HIDE_SHORTS_SUBSCRIPTIONS = new BooleanSetting("revanced_hide_shorts_subscriptions", FALSE); public static final BooleanSetting HIDE_SHORTS_SEARCH = new BooleanSetting("revanced_hide_shorts_search", FALSE); public static final BooleanSetting HIDE_SHORTS_JOIN_BUTTON = new BooleanSetting("revanced_hide_shorts_join_button", TRUE); public static final BooleanSetting HIDE_SHORTS_SUBSCRIBE_BUTTON = new BooleanSetting("revanced_hide_shorts_subscribe_button", TRUE); public static final BooleanSetting HIDE_SHORTS_PAUSED_OVERLAY_BUTTONS = new BooleanSetting("revanced_hide_shorts_paused_overlay_buttons", FALSE); public static final BooleanSetting HIDE_SHORTS_SHOP_BUTTON = new BooleanSetting("revanced_hide_shorts_shop_button", TRUE); public static final BooleanSetting HIDE_SHORTS_TAGGED_PRODUCTS = new BooleanSetting("revanced_hide_shorts_tagged_products", TRUE); public static final BooleanSetting HIDE_SHORTS_LOCATION_LABEL = new BooleanSetting("revanced_hide_shorts_location_label", FALSE); public static final BooleanSetting HIDE_SHORTS_SAVE_SOUND_BUTTON = new BooleanSetting("revanced_hide_shorts_save_sound_button", FALSE); public static final BooleanSetting HIDE_SHORTS_SEARCH_SUGGESTIONS = new BooleanSetting("revanced_hide_shorts_search_suggestions", FALSE); public static final BooleanSetting HIDE_SHORTS_LIKE_BUTTON = new BooleanSetting("revanced_hide_shorts_like_button", FALSE); public static final BooleanSetting HIDE_SHORTS_DISLIKE_BUTTON = new BooleanSetting("revanced_hide_shorts_dislike_button", FALSE); public static final BooleanSetting HIDE_SHORTS_COMMENTS_BUTTON = new BooleanSetting("revanced_hide_shorts_comments_button", FALSE); public static final BooleanSetting HIDE_SHORTS_REMIX_BUTTON = new BooleanSetting("revanced_hide_shorts_remix_button", TRUE); public static final BooleanSetting HIDE_SHORTS_SHARE_BUTTON = new BooleanSetting("revanced_hide_shorts_share_button", FALSE); public static final BooleanSetting HIDE_SHORTS_INFO_PANEL = new BooleanSetting("revanced_hide_shorts_info_panel", TRUE); public static final BooleanSetting HIDE_SHORTS_SOUND_BUTTON = new BooleanSetting("revanced_hide_shorts_sound_button", FALSE); public static final BooleanSetting HIDE_SHORTS_CHANNEL_BAR = new BooleanSetting("revanced_hide_shorts_channel_bar", FALSE); public static final BooleanSetting HIDE_SHORTS_VIDEO_TITLE = new BooleanSetting("revanced_hide_shorts_video_title", FALSE); public static final BooleanSetting HIDE_SHORTS_SOUND_METADATA_LABEL = new BooleanSetting("revanced_hide_shorts_sound_metadata_label", FALSE); public static final BooleanSetting HIDE_SHORTS_FULL_VIDEO_LINK_LABEL = new BooleanSetting("revanced_hide_shorts_full_video_link_label", FALSE); public static final BooleanSetting HIDE_SHORTS_NAVIGATION_BAR = new BooleanSetting("revanced_hide_shorts_navigation_bar", TRUE, true); // Seekbar public static final BooleanSetting RESTORE_OLD_SEEKBAR_THUMBNAILS = new BooleanSetting("revanced_restore_old_seekbar_thumbnails", TRUE); public static final BooleanSetting HIDE_SEEKBAR = new BooleanSetting("revanced_hide_seekbar", FALSE, true); public static final BooleanSetting HIDE_SEEKBAR_THUMBNAIL = new BooleanSetting("revanced_hide_seekbar_thumbnail", FALSE); public static final BooleanSetting SEEKBAR_CUSTOM_COLOR = new BooleanSetting("revanced_seekbar_custom_color", FALSE, true); public static final StringSetting SEEKBAR_CUSTOM_COLOR_VALUE = new StringSetting("revanced_seekbar_custom_color_value", "#FF0000", true, parent(SEEKBAR_CUSTOM_COLOR)); // Action buttons public static final BooleanSetting HIDE_LIKE_DISLIKE_BUTTON = new BooleanSetting("revanced_hide_like_dislike_button", FALSE); public static final BooleanSetting HIDE_SHARE_BUTTON = new BooleanSetting("revanced_hide_share_button", FALSE); public static final BooleanSetting HIDE_REPORT_BUTTON = new BooleanSetting("revanced_hide_report_button", FALSE); public static final BooleanSetting HIDE_REMIX_BUTTON = new BooleanSetting("revanced_hide_remix_button", TRUE); public static final BooleanSetting HIDE_DOWNLOAD_BUTTON = new BooleanSetting("revanced_hide_download_button", FALSE); public static final BooleanSetting HIDE_THANKS_BUTTON = new BooleanSetting("revanced_hide_thanks_button", TRUE); public static final BooleanSetting HIDE_CLIP_BUTTON = new BooleanSetting("revanced_hide_clip_button", TRUE); public static final BooleanSetting HIDE_PLAYLIST_BUTTON = new BooleanSetting("revanced_hide_playlist_button", FALSE); public static final BooleanSetting HIDE_SHOP_BUTTON = new BooleanSetting("revanced_hide_shop_button", TRUE); // Player flyout menu items public static final BooleanSetting HIDE_CAPTIONS_MENU = new BooleanSetting("revanced_hide_player_flyout_captions", FALSE); public static final BooleanSetting HIDE_ADDITIONAL_SETTINGS_MENU = new BooleanSetting("revanced_hide_player_flyout_additional_settings", FALSE); public static final BooleanSetting HIDE_LOOP_VIDEO_MENU = new BooleanSetting("revanced_hide_player_flyout_loop_video", FALSE); public static final BooleanSetting HIDE_AMBIENT_MODE_MENU = new BooleanSetting("revanced_hide_player_flyout_ambient_mode", FALSE); public static final BooleanSetting HIDE_REPORT_MENU = new BooleanSetting("revanced_hide_player_flyout_report", TRUE); public static final BooleanSetting HIDE_HELP_MENU = new BooleanSetting("revanced_hide_player_flyout_help", TRUE); public static final BooleanSetting HIDE_SPEED_MENU = new BooleanSetting("revanced_hide_player_flyout_speed", FALSE); public static final BooleanSetting HIDE_MORE_INFO_MENU = new BooleanSetting("revanced_hide_player_flyout_more_info", TRUE); public static final BooleanSetting HIDE_LOCK_SCREEN_MENU = new BooleanSetting("revanced_hide_player_flyout_lock_screen", FALSE); public static final BooleanSetting HIDE_AUDIO_TRACK_MENU = new BooleanSetting("revanced_hide_player_flyout_audio_track", FALSE); public static final BooleanSetting HIDE_WATCH_IN_VR_MENU = new BooleanSetting("revanced_hide_player_flyout_watch_in_vr", TRUE); // Misc public static final BooleanSetting AUTO_CAPTIONS = new BooleanSetting("revanced_auto_captions", FALSE); public static final BooleanSetting DISABLE_ZOOM_HAPTICS = new BooleanSetting("revanced_disable_zoom_haptics", TRUE); public static final BooleanSetting EXTERNAL_BROWSER = new BooleanSetting("revanced_external_browser", TRUE, true); public static final BooleanSetting AUTO_REPEAT = new BooleanSetting("revanced_auto_repeat", FALSE); public static final BooleanSetting SEEKBAR_TAPPING = new BooleanSetting("revanced_seekbar_tapping", TRUE); public static final BooleanSetting SLIDE_TO_SEEK = new BooleanSetting("revanced_slide_to_seek", FALSE); public static final BooleanSetting DISABLE_PRECISE_SEEKING_GESTURE = new BooleanSetting("revanced_disable_precise_seeking_gesture", TRUE); public static final BooleanSetting SPOOF_SIGNATURE = new BooleanSetting("revanced_spoof_signature_verification_enabled", TRUE, true, "revanced_spoof_signature_verification_enabled_user_dialog_message"); public static final BooleanSetting SPOOF_SIGNATURE_IN_FEED = new BooleanSetting("revanced_spoof_signature_in_feed_enabled", FALSE, false, parent(SPOOF_SIGNATURE)); public static final BooleanSetting SPOOF_STORYBOARD_RENDERER = new BooleanSetting("revanced_spoof_storyboard", TRUE, true, parent(SPOOF_SIGNATURE)); public static final BooleanSetting SPOOF_DEVICE_DIMENSIONS = new BooleanSetting("revanced_spoof_device_dimensions", FALSE, true, "revanced_spoof_device_dimensions_user_dialog_message"); public static final BooleanSetting BYPASS_URL_REDIRECTS = new BooleanSetting("revanced_bypass_url_redirects", TRUE); public static final BooleanSetting ANNOUNCEMENTS = new BooleanSetting("revanced_announcements", TRUE); @Deprecated public static final StringSetting DEPRECATED_ANNOUNCEMENT_LAST_HASH = new StringSetting("revanced_announcement_last_hash", ""); public static final IntegerSetting ANNOUNCEMENT_LAST_ID = new IntegerSetting("revanced_announcement_last_id", -1); public static final BooleanSetting REMOVE_TRACKING_QUERY_PARAMETER = new BooleanSetting("revanced_remove_tracking_query_parameter", TRUE); public static final BooleanSetting REMOVE_VIEWER_DISCRETION_DIALOG= new BooleanSetting("revanced_remove_viewer_discretion_dialog", FALSE, "revanced_remove_viewer_discretion_dialog_user_dialog_message"); // Swipe controls public static final BooleanSetting SWIPE_BRIGHTNESS = new BooleanSetting("revanced_swipe_brightness", TRUE); public static final BooleanSetting SWIPE_VOLUME = new BooleanSetting("revanced_swipe_volume", TRUE); public static final BooleanSetting SWIPE_PRESS_TO_ENGAGE = new BooleanSetting("revanced_swipe_press_to_engage", FALSE, true, parentsAny(SWIPE_BRIGHTNESS, SWIPE_VOLUME)); public static final BooleanSetting SWIPE_HAPTIC_FEEDBACK = new BooleanSetting("revanced_swipe_haptic_feedback", TRUE, true, parentsAny(SWIPE_BRIGHTNESS, SWIPE_VOLUME)); public static final IntegerSetting SWIPE_MAGNITUDE_THRESHOLD = new IntegerSetting("revanced_swipe_threshold", 30, true, parentsAny(SWIPE_BRIGHTNESS, SWIPE_VOLUME)); public static final IntegerSetting SWIPE_OVERLAY_BACKGROUND_ALPHA = new IntegerSetting("revanced_swipe_overlay_background_alpha", 127, true, parentsAny(SWIPE_BRIGHTNESS, SWIPE_VOLUME)); public static final IntegerSetting SWIPE_OVERLAY_TEXT_SIZE = new IntegerSetting("revanced_swipe_text_overlay_size", 22, true, parentsAny(SWIPE_BRIGHTNESS, SWIPE_VOLUME)); public static final LongSetting SWIPE_OVERLAY_TIMEOUT = new LongSetting("revanced_swipe_overlay_timeout", 500L, true, parentsAny(SWIPE_BRIGHTNESS, SWIPE_VOLUME)); public static final BooleanSetting SWIPE_SAVE_AND_RESTORE_BRIGHTNESS = new BooleanSetting("revanced_swipe_save_and_restore_brightness", TRUE, true, parent(SWIPE_BRIGHTNESS)); public static final FloatSetting SWIPE_BRIGHTNESS_VALUE = new FloatSetting("revanced_swipe_brightness_value", -1f); public static final BooleanSetting SWIPE_LOWEST_VALUE_ENABLE_AUTO_BRIGHTNESS = new BooleanSetting("revanced_swipe_lowest_value_enable_auto_brightness", FALSE, true, parent(SWIPE_BRIGHTNESS)); // Debugging /** * When enabled, share the debug logs with care. * The buffer contains select user data, including the client ip address and information that could identify the YT account. */ public static final BooleanSetting DEBUG_PROTOBUFFER = new BooleanSetting("revanced_debug_protobuffer", FALSE, parent(BaseSettings.DEBUG)); // ReturnYoutubeDislike public static final BooleanSetting RYD_ENABLED = new BooleanSetting("ryd_enabled", TRUE); public static final StringSetting RYD_USER_ID = new StringSetting("ryd_user_id", "", false, false); public static final BooleanSetting RYD_SHORTS = new BooleanSetting("ryd_shorts", TRUE, parent(RYD_ENABLED)); public static final BooleanSetting RYD_DISLIKE_PERCENTAGE = new BooleanSetting("ryd_dislike_percentage", FALSE, parent(RYD_ENABLED)); public static final BooleanSetting RYD_COMPACT_LAYOUT = new BooleanSetting("ryd_compact_layout", FALSE, parent(RYD_ENABLED)); public static final BooleanSetting RYD_TOAST_ON_CONNECTION_ERROR = new BooleanSetting("ryd_toast_on_connection_error", TRUE, parent(RYD_ENABLED)); // SponsorBlock public static final BooleanSetting SB_ENABLED = new BooleanSetting("sb_enabled", TRUE); /** * Do not use directly, instead use {@link SponsorBlockSettings} */ public static final StringSetting SB_PRIVATE_USER_ID = new StringSetting("sb_private_user_id_Do_Not_Share", ""); @Deprecated public static final StringSetting DEPRECATED_SB_UUID_OLD_MIGRATION_SETTING = new StringSetting("uuid", ""); // Delete sometime in 2024 public static final IntegerSetting SB_CREATE_NEW_SEGMENT_STEP = new IntegerSetting("sb_create_new_segment_step", 150, parent(SB_ENABLED)); public static final BooleanSetting SB_VOTING_BUTTON = new BooleanSetting("sb_voting_button", FALSE, parent(SB_ENABLED)); public static final BooleanSetting SB_CREATE_NEW_SEGMENT = new BooleanSetting("sb_create_new_segment", FALSE, parent(SB_ENABLED)); public static final BooleanSetting SB_COMPACT_SKIP_BUTTON = new BooleanSetting("sb_compact_skip_button", FALSE, parent(SB_ENABLED)); public static final BooleanSetting SB_AUTO_HIDE_SKIP_BUTTON = new BooleanSetting("sb_auto_hide_skip_button", TRUE, parent(SB_ENABLED)); public static final BooleanSetting SB_TOAST_ON_SKIP = new BooleanSetting("sb_toast_on_skip", TRUE, parent(SB_ENABLED)); public static final BooleanSetting SB_TOAST_ON_CONNECTION_ERROR = new BooleanSetting("sb_toast_on_connection_error", TRUE, parent(SB_ENABLED)); public static final BooleanSetting SB_TRACK_SKIP_COUNT = new BooleanSetting("sb_track_skip_count", TRUE, parent(SB_ENABLED)); public static final FloatSetting SB_SEGMENT_MIN_DURATION = new FloatSetting("sb_min_segment_duration", 0F, parent(SB_ENABLED)); public static final BooleanSetting SB_VIDEO_LENGTH_WITHOUT_SEGMENTS = new BooleanSetting("sb_video_length_without_segments", TRUE, parent(SB_ENABLED)); public static final StringSetting SB_API_URL = new StringSetting("sb_api_url","https://sponsor.ajay.app"); public static final BooleanSetting SB_USER_IS_VIP = new BooleanSetting("sb_user_is_vip", FALSE); public static final IntegerSetting SB_LOCAL_TIME_SAVED_NUMBER_SEGMENTS = new IntegerSetting("sb_local_time_saved_number_segments", 0); public static final LongSetting SB_LOCAL_TIME_SAVED_MILLISECONDS = new LongSetting("sb_local_time_saved_milliseconds", 0L); public static final StringSetting SB_CATEGORY_SPONSOR = new StringSetting("sb_sponsor", SKIP_AUTOMATICALLY_ONCE.reVancedKeyValue); public static final StringSetting SB_CATEGORY_SPONSOR_COLOR = new StringSetting("sb_sponsor_color","#00D400"); public static final StringSetting SB_CATEGORY_SELF_PROMO = new StringSetting("sb_selfpromo", MANUAL_SKIP.reVancedKeyValue); public static final StringSetting SB_CATEGORY_SELF_PROMO_COLOR = new StringSetting("sb_selfpromo_color","#FFFF00"); public static final StringSetting SB_CATEGORY_INTERACTION = new StringSetting("sb_interaction", MANUAL_SKIP.reVancedKeyValue); public static final StringSetting SB_CATEGORY_INTERACTION_COLOR = new StringSetting("sb_interaction_color","#CC00FF"); public static final StringSetting SB_CATEGORY_HIGHLIGHT = new StringSetting("sb_highlight", MANUAL_SKIP.reVancedKeyValue); public static final StringSetting SB_CATEGORY_HIGHLIGHT_COLOR = new StringSetting("sb_highlight_color","#FF1684"); public static final StringSetting SB_CATEGORY_INTRO = new StringSetting("sb_intro", MANUAL_SKIP.reVancedKeyValue); public static final StringSetting SB_CATEGORY_INTRO_COLOR = new StringSetting("sb_intro_color","#00FFFF"); public static final StringSetting SB_CATEGORY_OUTRO = new StringSetting("sb_outro", MANUAL_SKIP.reVancedKeyValue); public static final StringSetting SB_CATEGORY_OUTRO_COLOR = new StringSetting("sb_outro_color","#0202ED"); public static final StringSetting SB_CATEGORY_PREVIEW = new StringSetting("sb_preview", IGNORE.reVancedKeyValue); public static final StringSetting SB_CATEGORY_PREVIEW_COLOR = new StringSetting("sb_preview_color","#008FD6"); public static final StringSetting SB_CATEGORY_FILLER = new StringSetting("sb_filler", IGNORE.reVancedKeyValue); public static final StringSetting SB_CATEGORY_FILLER_COLOR = new StringSetting("sb_filler_color","#7300FF"); public static final StringSetting SB_CATEGORY_MUSIC_OFFTOPIC = new StringSetting("sb_music_offtopic", MANUAL_SKIP.reVancedKeyValue); public static final StringSetting SB_CATEGORY_MUSIC_OFFTOPIC_COLOR = new StringSetting("sb_music_offtopic_color","#FF9900"); public static final StringSetting SB_CATEGORY_UNSUBMITTED = new StringSetting("sb_unsubmitted", SKIP_AUTOMATICALLY.reVancedKeyValue); public static final StringSetting SB_CATEGORY_UNSUBMITTED_COLOR = new StringSetting("sb_unsubmitted_color","#FFFFFF"); // SB Setting not exported public static final LongSetting SB_LAST_VIP_CHECK = new LongSetting("sb_last_vip_check", 0L, false, false); public static final BooleanSetting SB_HIDE_EXPORT_WARNING = new BooleanSetting("sb_hide_export_warning", FALSE, false, false); public static final BooleanSetting SB_SEEN_GUIDELINES = new BooleanSetting("sb_seen_guidelines", FALSE, false, false); static { // region Migration // Migrate settings from old Preference categories into replacement "revanced_prefs" category. // This region must run before all other migration code. // The YT and RYD migration portion of this can be removed anytime, // but the SB migration should remain until late 2024 or early 2025 // because it migrates the SB private user id which cannot be recovered if lost. // Categories were previously saved without a 'sb_' key prefix, so they need an additional adjustment. Set<Setting<?>> sbCategories = new HashSet<>(Arrays.asList( SB_CATEGORY_SPONSOR, SB_CATEGORY_SPONSOR_COLOR, SB_CATEGORY_SELF_PROMO, SB_CATEGORY_SELF_PROMO_COLOR, SB_CATEGORY_INTERACTION, SB_CATEGORY_INTERACTION_COLOR, SB_CATEGORY_HIGHLIGHT, SB_CATEGORY_HIGHLIGHT_COLOR, SB_CATEGORY_INTRO, SB_CATEGORY_INTRO_COLOR, SB_CATEGORY_OUTRO, SB_CATEGORY_OUTRO_COLOR, SB_CATEGORY_PREVIEW, SB_CATEGORY_PREVIEW_COLOR, SB_CATEGORY_FILLER, SB_CATEGORY_FILLER_COLOR, SB_CATEGORY_MUSIC_OFFTOPIC, SB_CATEGORY_MUSIC_OFFTOPIC_COLOR, SB_CATEGORY_UNSUBMITTED, SB_CATEGORY_UNSUBMITTED_COLOR)); SharedPrefCategory ytPrefs = new SharedPrefCategory("youtube"); SharedPrefCategory rydPrefs = new SharedPrefCategory("ryd"); SharedPrefCategory sbPrefs = new SharedPrefCategory("sponsor-block"); for (Setting<?> setting : Setting.allLoadedSettings()) { String key = setting.key; if (setting.key.startsWith("sb_")) { if (sbCategories.contains(setting)) { key = key.substring(3); // Remove the "sb_" prefix, as old categories are saved without it. } migrateFromOldPreferences(sbPrefs, setting, key); } else if (setting.key.startsWith("ryd_")) { migrateFromOldPreferences(rydPrefs, setting, key); } else { migrateFromOldPreferences(ytPrefs, setting, key); } } // Do _not_ delete this SB private user id migration property until sometime in 2024. // This is the only setting that cannot be reconfigured if lost, // and more time should be given for users who rarely upgrade. migrateOldSettingToNew(DEPRECATED_SB_UUID_OLD_MIGRATION_SETTING, SB_PRIVATE_USER_ID); // Old spoof versions that no longer work reliably. if (SpoofAppVersionPatch.isSpoofingToLessThan("17.33.00")) { Logger.printInfo(() -> "Resetting spoof app version target"); Settings.SPOOF_APP_VERSION_TARGET.resetToDefault(); } // Remove any previously saved announcement consumer (a random generated string). Setting.preferences.removeKey("revanced_announcement_consumer"); // Shorts if (DEPRECATED_HIDE_SHORTS.get()) { Logger.printInfo(() -> "Migrating hide Shorts setting"); DEPRECATED_HIDE_SHORTS.resetToDefault(); HIDE_SHORTS_HOME.save(true); HIDE_SHORTS_SUBSCRIPTIONS.save(true); HIDE_SHORTS_SEARCH.save(true); } migrateOldSettingToNew(HIDE_LOAD_MORE_BUTTON, HIDE_SHOW_MORE_BUTTON); // endregion } }
37,133
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
LicenseActivityHook.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/settings/LicenseActivityHook.java
package app.revanced.integrations.youtube.settings; import android.annotation.SuppressLint; import android.app.Activity; import android.preference.PreferenceFragment; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.youtube.ThemeHelper; import app.revanced.integrations.youtube.settings.preference.ReVancedPreferenceFragment; import app.revanced.integrations.youtube.settings.preference.ReturnYouTubeDislikePreferenceFragment; import app.revanced.integrations.youtube.settings.preference.SponsorBlockPreferenceFragment; import java.util.Objects; import static app.revanced.integrations.shared.Utils.getChildView; import static app.revanced.integrations.shared.Utils.getResourceIdentifier; /** * Hooks LicenseActivity. * <p> * This class is responsible for injecting our own fragment by replacing the LicenseActivity. */ @SuppressWarnings("unused") public class LicenseActivityHook { /** * Injection point. * <p> * Hooks LicenseActivity#onCreate in order to inject our own fragment. */ public static void initialize(Activity licenseActivity) { try { ThemeHelper.setActivityTheme(licenseActivity); licenseActivity.setContentView( getResourceIdentifier("revanced_settings_with_toolbar", "layout")); setBackButton(licenseActivity); PreferenceFragment fragment; String toolbarTitleResourceName; String dataString = licenseActivity.getIntent().getDataString(); switch (dataString) { case "revanced_sb_settings_intent": toolbarTitleResourceName = "revanced_sb_settings_title"; fragment = new SponsorBlockPreferenceFragment(); break; case "revanced_ryd_settings_intent": toolbarTitleResourceName = "revanced_ryd_settings_title"; fragment = new ReturnYouTubeDislikePreferenceFragment(); break; case "revanced_settings_intent": toolbarTitleResourceName = "revanced_settings_title"; fragment = new ReVancedPreferenceFragment(); break; default: Logger.printException(() -> "Unknown setting: " + dataString); return; } setToolbarTitle(licenseActivity, toolbarTitleResourceName); licenseActivity.getFragmentManager() .beginTransaction() .replace(getResourceIdentifier("revanced_settings_fragments", "id"), fragment) .commit(); } catch (Exception ex) { Logger.printException(() -> "onCreate failure", ex); } } private static void setToolbarTitle(Activity activity, String toolbarTitleResourceName) { ViewGroup toolbar = activity.findViewById(getToolbarResourceId()); TextView toolbarTextView = Objects.requireNonNull(getChildView(toolbar, false, view -> view instanceof TextView)); toolbarTextView.setText(getResourceIdentifier(toolbarTitleResourceName, "string")); } @SuppressLint("UseCompatLoadingForDrawables") private static void setBackButton(Activity activity) { ViewGroup toolbar = activity.findViewById(getToolbarResourceId()); ImageButton imageButton = Objects.requireNonNull(getChildView(toolbar, false, view -> view instanceof ImageButton)); final int backButtonResource = getResourceIdentifier(ThemeHelper.isDarkTheme() ? "yt_outline_arrow_left_white_24" : "yt_outline_arrow_left_black_24", "drawable"); imageButton.setImageDrawable(activity.getResources().getDrawable(backButtonResource)); imageButton.setOnClickListener(view -> activity.onBackPressed()); } private static int getToolbarResourceId() { final int toolbarResourceId = getResourceIdentifier("revanced_toolbar", "id"); if (toolbarResourceId == 0) { throw new IllegalStateException("Could not find back button resource"); } return toolbarResourceId; } }
4,342
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ReturnYouTubeDislikePreferenceFragment.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/settings/preference/ReturnYouTubeDislikePreferenceFragment.java
package app.revanced.integrations.youtube.settings.preference; import static app.revanced.integrations.shared.StringRef.str; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.preference.SwitchPreference; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.settings.Setting; import app.revanced.integrations.shared.settings.BaseSettings; import app.revanced.integrations.youtube.patches.ReturnYouTubeDislikePatch; import app.revanced.integrations.youtube.returnyoutubedislike.ReturnYouTubeDislike; import app.revanced.integrations.youtube.returnyoutubedislike.requests.ReturnYouTubeDislikeApi; import app.revanced.integrations.youtube.settings.Settings; /** @noinspection deprecation*/ public class ReturnYouTubeDislikePreferenceFragment extends PreferenceFragment { /** * If dislikes are shown on Shorts. */ private SwitchPreference shortsPreference; /** * If dislikes are shown as percentage. */ private SwitchPreference percentagePreference; /** * If segmented like/dislike button uses smaller compact layout. */ private SwitchPreference compactLayoutPreference; /** * If segmented like/dislike button uses smaller compact layout. */ private SwitchPreference toastOnRYDNotAvailable; private void updateUIState() { shortsPreference.setEnabled(Settings.RYD_SHORTS.isAvailable()); percentagePreference.setEnabled(Settings.RYD_DISLIKE_PERCENTAGE.isAvailable()); compactLayoutPreference.setEnabled(Settings.RYD_COMPACT_LAYOUT.isAvailable()); toastOnRYDNotAvailable.setEnabled(Settings.RYD_TOAST_ON_CONNECTION_ERROR.isAvailable()); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { Activity context = getActivity(); PreferenceManager manager = getPreferenceManager(); manager.setSharedPreferencesName(Setting.preferences.name); PreferenceScreen preferenceScreen = manager.createPreferenceScreen(context); setPreferenceScreen(preferenceScreen); SwitchPreference enabledPreference = new SwitchPreference(context); enabledPreference.setChecked(Settings.RYD_ENABLED.get()); enabledPreference.setTitle(str("revanced_ryd_enable_title")); enabledPreference.setSummaryOn(str("revanced_ryd_enable_summary_on")); enabledPreference.setSummaryOff(str("revanced_ryd_enable_summary_off")); enabledPreference.setOnPreferenceChangeListener((pref, newValue) -> { final Boolean rydIsEnabled = (Boolean) newValue; Settings.RYD_ENABLED.save(rydIsEnabled); ReturnYouTubeDislikePatch.onRYDStatusChange(rydIsEnabled); updateUIState(); return true; }); preferenceScreen.addPreference(enabledPreference); shortsPreference = new SwitchPreference(context); shortsPreference.setChecked(Settings.RYD_SHORTS.get()); shortsPreference.setTitle(str("revanced_ryd_shorts_title")); String shortsSummary = ReturnYouTubeDislikePatch.IS_SPOOFING_TO_NON_LITHO_SHORTS_PLAYER ? str("revanced_ryd_shorts_summary_on") : str("revanced_ryd_shorts_summary_on_disclaimer"); shortsPreference.setSummaryOn(shortsSummary); shortsPreference.setSummaryOff(str("revanced_ryd_shorts_summary_off")); shortsPreference.setOnPreferenceChangeListener((pref, newValue) -> { Settings.RYD_SHORTS.save((Boolean) newValue); updateUIState(); return true; }); preferenceScreen.addPreference(shortsPreference); percentagePreference = new SwitchPreference(context); percentagePreference.setChecked(Settings.RYD_DISLIKE_PERCENTAGE.get()); percentagePreference.setTitle(str("revanced_ryd_dislike_percentage_title")); percentagePreference.setSummaryOn(str("revanced_ryd_dislike_percentage_summary_on")); percentagePreference.setSummaryOff(str("revanced_ryd_dislike_percentage_summary_off")); percentagePreference.setOnPreferenceChangeListener((pref, newValue) -> { Settings.RYD_DISLIKE_PERCENTAGE.save((Boolean) newValue); ReturnYouTubeDislike.clearAllUICaches(); updateUIState(); return true; }); preferenceScreen.addPreference(percentagePreference); compactLayoutPreference = new SwitchPreference(context); compactLayoutPreference.setChecked(Settings.RYD_COMPACT_LAYOUT.get()); compactLayoutPreference.setTitle(str("revanced_ryd_compact_layout_title")); compactLayoutPreference.setSummaryOn(str("revanced_ryd_compact_layout_summary_on")); compactLayoutPreference.setSummaryOff(str("revanced_ryd_compact_layout_summary_off")); compactLayoutPreference.setOnPreferenceChangeListener((pref, newValue) -> { Settings.RYD_COMPACT_LAYOUT.save((Boolean) newValue); ReturnYouTubeDislike.clearAllUICaches(); updateUIState(); return true; }); preferenceScreen.addPreference(compactLayoutPreference); toastOnRYDNotAvailable = new SwitchPreference(context); toastOnRYDNotAvailable.setChecked(Settings.RYD_TOAST_ON_CONNECTION_ERROR.get()); toastOnRYDNotAvailable.setTitle(str("revanced_ryd_toast_on_connection_error_title")); toastOnRYDNotAvailable.setSummaryOn(str("revanced_ryd_toast_on_connection_error_summary_on")); toastOnRYDNotAvailable.setSummaryOff(str("revanced_ryd_toast_on_connection_error_summary_off")); toastOnRYDNotAvailable.setOnPreferenceChangeListener((pref, newValue) -> { Settings.RYD_TOAST_ON_CONNECTION_ERROR.save((Boolean) newValue); updateUIState(); return true; }); preferenceScreen.addPreference(toastOnRYDNotAvailable); updateUIState(); // About category PreferenceCategory aboutCategory = new PreferenceCategory(context); aboutCategory.setTitle(str("revanced_ryd_about")); preferenceScreen.addPreference(aboutCategory); // ReturnYouTubeDislike Website Preference aboutWebsitePreference = new Preference(context); aboutWebsitePreference.setTitle(str("revanced_ryd_attribution_title")); aboutWebsitePreference.setSummary(str("revanced_ryd_attribution_summary")); aboutWebsitePreference.setOnPreferenceClickListener(pref -> { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://returnyoutubedislike.com")); pref.getContext().startActivity(i); return false; }); aboutCategory.addPreference(aboutWebsitePreference); // RYD API connection statistics if (BaseSettings.DEBUG.get()) { PreferenceCategory emptyCategory = new PreferenceCategory(context); // vertical padding preferenceScreen.addPreference(emptyCategory); PreferenceCategory statisticsCategory = new PreferenceCategory(context); statisticsCategory.setTitle(str("revanced_ryd_statistics_category_title")); preferenceScreen.addPreference(statisticsCategory); Preference statisticPreference; statisticPreference = new Preference(context); statisticPreference.setSelectable(false); statisticPreference.setTitle(str("revanced_ryd_statistics_getFetchCallResponseTimeAverage_title")); statisticPreference.setSummary(createMillisecondStringFromNumber(ReturnYouTubeDislikeApi.getFetchCallResponseTimeAverage())); preferenceScreen.addPreference(statisticPreference); statisticPreference = new Preference(context); statisticPreference.setSelectable(false); statisticPreference.setTitle(str("revanced_ryd_statistics_getFetchCallResponseTimeMin_title")); statisticPreference.setSummary(createMillisecondStringFromNumber(ReturnYouTubeDislikeApi.getFetchCallResponseTimeMin())); preferenceScreen.addPreference(statisticPreference); statisticPreference = new Preference(context); statisticPreference.setSelectable(false); statisticPreference.setTitle(str("revanced_ryd_statistics_getFetchCallResponseTimeMax_title")); statisticPreference.setSummary(createMillisecondStringFromNumber(ReturnYouTubeDislikeApi.getFetchCallResponseTimeMax())); preferenceScreen.addPreference(statisticPreference); String fetchCallTimeWaitingLastSummary; final long fetchCallTimeWaitingLast = ReturnYouTubeDislikeApi.getFetchCallResponseTimeLast(); if (fetchCallTimeWaitingLast == ReturnYouTubeDislikeApi.FETCH_CALL_RESPONSE_TIME_VALUE_RATE_LIMIT) { fetchCallTimeWaitingLastSummary = str("revanced_ryd_statistics_getFetchCallResponseTimeLast_rate_limit_summary"); } else { fetchCallTimeWaitingLastSummary = createMillisecondStringFromNumber(fetchCallTimeWaitingLast); } statisticPreference = new Preference(context); statisticPreference.setSelectable(false); statisticPreference.setTitle(str("revanced_ryd_statistics_getFetchCallResponseTimeLast_title")); statisticPreference.setSummary(fetchCallTimeWaitingLastSummary); preferenceScreen.addPreference(statisticPreference); statisticPreference = new Preference(context); statisticPreference.setSelectable(false); statisticPreference.setTitle(str("revanced_ryd_statistics_getFetchCallCount_title")); statisticPreference.setSummary(createSummaryText(ReturnYouTubeDislikeApi.getFetchCallCount(), "revanced_ryd_statistics_getFetchCallCount_zero_summary", "revanced_ryd_statistics_getFetchCallCount_non_zero_summary")); preferenceScreen.addPreference(statisticPreference); statisticPreference = new Preference(context); statisticPreference.setSelectable(false); statisticPreference.setTitle(str("revanced_ryd_statistics_getFetchCallNumberOfFailures_title")); statisticPreference.setSummary(createSummaryText(ReturnYouTubeDislikeApi.getFetchCallNumberOfFailures(), "revanced_ryd_statistics_getFetchCallNumberOfFailures_zero_summary", "revanced_ryd_statistics_getFetchCallNumberOfFailures_non_zero_summary")); preferenceScreen.addPreference(statisticPreference); statisticPreference = new Preference(context); statisticPreference.setSelectable(false); statisticPreference.setTitle(str("revanced_ryd_statistics_getNumberOfRateLimitRequestsEncountered_title")); statisticPreference.setSummary(createSummaryText(ReturnYouTubeDislikeApi.getNumberOfRateLimitRequestsEncountered(), "revanced_ryd_statistics_getNumberOfRateLimitRequestsEncountered_zero_summary", "revanced_ryd_statistics_getNumberOfRateLimitRequestsEncountered_non_zero_summary")); preferenceScreen.addPreference(statisticPreference); } } catch (Exception ex) { Logger.printException(() -> "onCreate failure", ex); } } private static String createSummaryText(int value, String summaryStringZeroKey, String summaryStringOneOrMoreKey) { if (value == 0) { return str(summaryStringZeroKey); } return String.format(str(summaryStringOneOrMoreKey), value); } private static String createMillisecondStringFromNumber(long number) { return String.format(str("revanced_ryd_statistics_millisecond_text"), number); } }
12,711
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ReVancedYouTubeAboutPreference.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/settings/preference/ReVancedYouTubeAboutPreference.java
package app.revanced.integrations.youtube.settings.preference; import android.content.Context; import android.util.AttributeSet; import app.revanced.integrations.shared.settings.preference.ReVancedAboutPreference; import app.revanced.integrations.youtube.ThemeHelper; @SuppressWarnings("unused") public class ReVancedYouTubeAboutPreference extends ReVancedAboutPreference { public int getLightColor() { return ThemeHelper.getLightThemeColor(); } public int getDarkColor() { return ThemeHelper.getDarkThemeColor(); } public ReVancedYouTubeAboutPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public ReVancedYouTubeAboutPreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public ReVancedYouTubeAboutPreference(Context context, AttributeSet attrs) { super(context, attrs); } public ReVancedYouTubeAboutPreference(Context context) { super(context); } }
1,095
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ReVancedPreferenceFragment.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/settings/preference/ReVancedPreferenceFragment.java
package app.revanced.integrations.youtube.settings.preference; import android.os.Build; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceGroup; import androidx.annotation.RequiresApi; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.settings.preference.AbstractPreferenceFragment; import app.revanced.integrations.youtube.patches.DownloadsPatch; import app.revanced.integrations.youtube.patches.playback.speed.CustomPlaybackSpeedPatch; import app.revanced.integrations.youtube.settings.Settings; /** * Preference fragment for ReVanced settings. * * @noinspection deprecation */ public class ReVancedPreferenceFragment extends AbstractPreferenceFragment { @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void initialize() { super.initialize(); try { // If the preference was included, then initialize it based on the available playback speed. Preference defaultSpeedPreference = findPreference(Settings.PLAYBACK_SPEED_DEFAULT.key); if (defaultSpeedPreference instanceof ListPreference) { CustomPlaybackSpeedPatch.initializeListPreference((ListPreference) defaultSpeedPreference); } } catch (Exception ex) { Logger.printException(() -> "initialize failure", ex); } } }
1,421
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
AlternativeThumbnailsAboutDeArrowPreference.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/settings/preference/AlternativeThumbnailsAboutDeArrowPreference.java
package app.revanced.integrations.youtube.settings.preference; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.preference.Preference; import android.util.AttributeSet; /** * Allows tapping the DeArrow about preference to open the DeArrow website. */ @SuppressWarnings({"unused", "deprecation"}) public class AlternativeThumbnailsAboutDeArrowPreference extends Preference { { setOnPreferenceClickListener(pref -> { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://dearrow.ajay.app")); pref.getContext().startActivity(i); return false; }); } public AlternativeThumbnailsAboutDeArrowPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public AlternativeThumbnailsAboutDeArrowPreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public AlternativeThumbnailsAboutDeArrowPreference(Context context, AttributeSet attrs) { super(context, attrs); } public AlternativeThumbnailsAboutDeArrowPreference(Context context) { super(context); } }
1,287
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
SponsorBlockPreferenceFragment.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/settings/preference/SponsorBlockPreferenceFragment.java
package app.revanced.integrations.youtube.settings.preference; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.*; import android.text.Html; import android.text.InputType; import android.util.TypedValue; import android.widget.EditText; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.shared.settings.Setting; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.youtube.sponsorblock.SegmentPlaybackController; import app.revanced.integrations.youtube.sponsorblock.SponsorBlockSettings; import app.revanced.integrations.youtube.sponsorblock.SponsorBlockUtils; import app.revanced.integrations.youtube.sponsorblock.objects.SegmentCategory; import app.revanced.integrations.youtube.sponsorblock.objects.SegmentCategoryListPreference; import app.revanced.integrations.youtube.sponsorblock.objects.UserStats; import app.revanced.integrations.youtube.sponsorblock.requests.SBRequester; import app.revanced.integrations.youtube.sponsorblock.ui.SponsorBlockViewController; import static android.text.Html.fromHtml; import static app.revanced.integrations.shared.StringRef.str; @SuppressWarnings("deprecation") public class SponsorBlockPreferenceFragment extends PreferenceFragment { private SwitchPreference sbEnabled; private SwitchPreference addNewSegment; private SwitchPreference votingEnabled; private SwitchPreference compactSkipButton; private SwitchPreference autoHideSkipSegmentButton; private SwitchPreference showSkipToast; private SwitchPreference trackSkips; private SwitchPreference showTimeWithoutSegments; private SwitchPreference toastOnConnectionError; private EditTextPreference newSegmentStep; private EditTextPreference minSegmentDuration; private EditTextPreference privateUserId; private EditTextPreference importExport; private Preference apiUrl; private PreferenceCategory statsCategory; private PreferenceCategory segmentCategory; private void updateUI() { try { final boolean enabled = Settings.SB_ENABLED.get(); if (!enabled) { SponsorBlockViewController.hideAll(); SegmentPlaybackController.setCurrentVideoId(null); } else if (!Settings.SB_CREATE_NEW_SEGMENT.get()) { SponsorBlockViewController.hideNewSegmentLayout(); } // Voting and add new segment buttons automatically shows/hide themselves. sbEnabled.setChecked(enabled); addNewSegment.setChecked(Settings.SB_CREATE_NEW_SEGMENT.get()); addNewSegment.setEnabled(enabled); votingEnabled.setChecked(Settings.SB_VOTING_BUTTON.get()); votingEnabled.setEnabled(enabled); compactSkipButton.setChecked(Settings.SB_COMPACT_SKIP_BUTTON.get()); compactSkipButton.setEnabled(enabled); autoHideSkipSegmentButton.setChecked(Settings.SB_AUTO_HIDE_SKIP_BUTTON.get()); autoHideSkipSegmentButton.setEnabled(enabled); showSkipToast.setChecked(Settings.SB_TOAST_ON_SKIP.get()); showSkipToast.setEnabled(enabled); toastOnConnectionError.setChecked(Settings.SB_TOAST_ON_CONNECTION_ERROR.get()); toastOnConnectionError.setEnabled(enabled); trackSkips.setChecked(Settings.SB_TRACK_SKIP_COUNT.get()); trackSkips.setEnabled(enabled); showTimeWithoutSegments.setChecked(Settings.SB_VIDEO_LENGTH_WITHOUT_SEGMENTS.get()); showTimeWithoutSegments.setEnabled(enabled); newSegmentStep.setText((Settings.SB_CREATE_NEW_SEGMENT_STEP.get()).toString()); newSegmentStep.setEnabled(enabled); minSegmentDuration.setText((Settings.SB_SEGMENT_MIN_DURATION.get()).toString()); minSegmentDuration.setEnabled(enabled); privateUserId.setText(Settings.SB_PRIVATE_USER_ID.get()); privateUserId.setEnabled(enabled); // If the user has a private user id, then include a subtext that mentions not to share it. String importExportSummary = SponsorBlockSettings.userHasSBPrivateId() ? str("revanced_sb_settings_ie_sum_warning") : str("revanced_sb_settings_ie_sum"); importExport.setSummary(importExportSummary); apiUrl.setEnabled(enabled); importExport.setEnabled(enabled); segmentCategory.setEnabled(enabled); statsCategory.setEnabled(enabled); } catch (Exception ex) { Logger.printException(() -> "update settings UI failure", ex); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { Activity context = getActivity(); PreferenceManager manager = getPreferenceManager(); manager.setSharedPreferencesName(Setting.preferences.name); PreferenceScreen preferenceScreen = manager.createPreferenceScreen(context); setPreferenceScreen(preferenceScreen); SponsorBlockSettings.initialize(); sbEnabled = new SwitchPreference(context); sbEnabled.setTitle(str("revanced_sb_enable_sb")); sbEnabled.setSummary(str("revanced_sb_enable_sb_sum")); preferenceScreen.addPreference(sbEnabled); sbEnabled.setOnPreferenceChangeListener((preference1, newValue) -> { Settings.SB_ENABLED.save((Boolean) newValue); updateUI(); return true; }); addAppearanceCategory(context, preferenceScreen); segmentCategory = new PreferenceCategory(context); segmentCategory.setTitle(str("revanced_sb_diff_segments")); preferenceScreen.addPreference(segmentCategory); updateSegmentCategories(); addCreateSegmentCategory(context, preferenceScreen); addGeneralCategory(context, preferenceScreen); statsCategory = new PreferenceCategory(context); statsCategory.setTitle(str("revanced_sb_stats")); preferenceScreen.addPreference(statsCategory); fetchAndDisplayStats(); addAboutCategory(context, preferenceScreen); updateUI(); } catch (Exception ex) { Logger.printException(() -> "onCreate failure", ex); } } private void addAppearanceCategory(Context context, PreferenceScreen screen) { PreferenceCategory category = new PreferenceCategory(context); screen.addPreference(category); category.setTitle(str("revanced_sb_appearance_category")); votingEnabled = new SwitchPreference(context); votingEnabled.setTitle(str("revanced_sb_enable_voting")); votingEnabled.setSummaryOn(str("revanced_sb_enable_voting_sum_on")); votingEnabled.setSummaryOff(str("revanced_sb_enable_voting_sum_off")); category.addPreference(votingEnabled); votingEnabled.setOnPreferenceChangeListener((preference1, newValue) -> { Settings.SB_VOTING_BUTTON.save((Boolean) newValue); updateUI(); return true; }); compactSkipButton = new SwitchPreference(context); compactSkipButton.setTitle(str("revanced_sb_enable_compact_skip_button")); compactSkipButton.setSummaryOn(str("revanced_sb_enable_compact_skip_button_sum_on")); compactSkipButton.setSummaryOff(str("revanced_sb_enable_compact_skip_button_sum_off")); category.addPreference(compactSkipButton); compactSkipButton.setOnPreferenceChangeListener((preference1, newValue) -> { Settings.SB_COMPACT_SKIP_BUTTON.save((Boolean) newValue); updateUI(); return true; }); autoHideSkipSegmentButton = new SwitchPreference(context); autoHideSkipSegmentButton.setTitle(str("revanced_sb_enable_auto_hide_skip_segment_button")); autoHideSkipSegmentButton.setSummaryOn(str("revanced_sb_enable_auto_hide_skip_segment_button_sum_on")); autoHideSkipSegmentButton.setSummaryOff(str("revanced_sb_enable_auto_hide_skip_segment_button_sum_off")); category.addPreference(autoHideSkipSegmentButton); autoHideSkipSegmentButton.setOnPreferenceChangeListener((preference1, newValue) -> { Settings.SB_AUTO_HIDE_SKIP_BUTTON.save((Boolean) newValue); updateUI(); return true; }); showSkipToast = new SwitchPreference(context); showSkipToast.setTitle(str("revanced_sb_general_skiptoast")); showSkipToast.setSummaryOn(str("revanced_sb_general_skiptoast_sum_on")); showSkipToast.setSummaryOff(str("revanced_sb_general_skiptoast_sum_off")); showSkipToast.setOnPreferenceClickListener(preference1 -> { Utils.showToastShort(str("revanced_sb_skipped_sponsor")); return false; }); showSkipToast.setOnPreferenceChangeListener((preference1, newValue) -> { Settings.SB_TOAST_ON_SKIP.save((Boolean) newValue); updateUI(); return true; }); category.addPreference(showSkipToast); showTimeWithoutSegments = new SwitchPreference(context); showTimeWithoutSegments.setTitle(str("revanced_sb_general_time_without")); showTimeWithoutSegments.setSummaryOn(str("revanced_sb_general_time_without_sum_on")); showTimeWithoutSegments.setSummaryOff(str("revanced_sb_general_time_without_sum_off")); showTimeWithoutSegments.setOnPreferenceChangeListener((preference1, newValue) -> { Settings.SB_VIDEO_LENGTH_WITHOUT_SEGMENTS.save((Boolean) newValue); updateUI(); return true; }); category.addPreference(showTimeWithoutSegments); } private void addCreateSegmentCategory(Context context, PreferenceScreen screen) { PreferenceCategory category = new PreferenceCategory(context); screen.addPreference(category); category.setTitle(str("revanced_sb_create_segment_category")); addNewSegment = new SwitchPreference(context); addNewSegment.setTitle(str("revanced_sb_enable_create_segment")); addNewSegment.setSummaryOn(str("revanced_sb_enable_create_segment_sum_on")); addNewSegment.setSummaryOff(str("revanced_sb_enable_create_segment_sum_off")); category.addPreference(addNewSegment); addNewSegment.setOnPreferenceChangeListener((preference1, o) -> { Boolean newValue = (Boolean) o; if (newValue && !Settings.SB_SEEN_GUIDELINES.get()) { new AlertDialog.Builder(preference1.getContext()) .setTitle(str("revanced_sb_guidelines_popup_title")) .setMessage(str("revanced_sb_guidelines_popup_content")) .setNegativeButton(str("revanced_sb_guidelines_popup_already_read"), null) .setPositiveButton(str("revanced_sb_guidelines_popup_open"), (dialogInterface, i) -> openGuidelines()) .setOnDismissListener(dialog -> Settings.SB_SEEN_GUIDELINES.save(true)) .setCancelable(false) .show(); } Settings.SB_CREATE_NEW_SEGMENT.save(newValue); updateUI(); return true; }); newSegmentStep = new EditTextPreference(context); newSegmentStep.setTitle(str("revanced_sb_general_adjusting")); newSegmentStep.setSummary(str("revanced_sb_general_adjusting_sum")); newSegmentStep.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER); newSegmentStep.setOnPreferenceChangeListener((preference1, newValue) -> { final int newAdjustmentValue = Integer.parseInt(newValue.toString()); if (newAdjustmentValue == 0) { Utils.showToastLong(str("revanced_sb_general_adjusting_invalid")); return false; } Settings.SB_CREATE_NEW_SEGMENT_STEP.save(newAdjustmentValue); return true; }); category.addPreference(newSegmentStep); Preference guidelinePreferences = new Preference(context); guidelinePreferences.setTitle(str("revanced_sb_guidelines_preference_title")); guidelinePreferences.setSummary(str("revanced_sb_guidelines_preference_sum")); guidelinePreferences.setOnPreferenceClickListener(preference1 -> { openGuidelines(); return true; }); category.addPreference(guidelinePreferences); } private void addGeneralCategory(final Context context, PreferenceScreen screen) { PreferenceCategory category = new PreferenceCategory(context); screen.addPreference(category); category.setTitle(str("revanced_sb_general")); toastOnConnectionError = new SwitchPreference(context); toastOnConnectionError.setTitle(str("revanced_sb_toast_on_connection_error_title")); toastOnConnectionError.setSummaryOn(str("revanced_sb_toast_on_connection_error_summary_on")); toastOnConnectionError.setSummaryOff(str("revanced_sb_toast_on_connection_error_summary_off")); toastOnConnectionError.setOnPreferenceChangeListener((preference1, newValue) -> { Settings.SB_TOAST_ON_CONNECTION_ERROR.save((Boolean) newValue); updateUI(); return true; }); category.addPreference(toastOnConnectionError); trackSkips = new SwitchPreference(context); trackSkips.setTitle(str("revanced_sb_general_skipcount")); trackSkips.setSummaryOn(str("revanced_sb_general_skipcount_sum_on")); trackSkips.setSummaryOff(str("revanced_sb_general_skipcount_sum_off")); trackSkips.setOnPreferenceChangeListener((preference1, newValue) -> { Settings.SB_TRACK_SKIP_COUNT.save((Boolean) newValue); updateUI(); return true; }); category.addPreference(trackSkips); minSegmentDuration = new EditTextPreference(context); minSegmentDuration.setTitle(str("revanced_sb_general_min_duration")); minSegmentDuration.setSummary(str("revanced_sb_general_min_duration_sum")); minSegmentDuration.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); minSegmentDuration.setOnPreferenceChangeListener((preference1, newValue) -> { Settings.SB_SEGMENT_MIN_DURATION.save(Float.valueOf(newValue.toString())); return true; }); category.addPreference(minSegmentDuration); privateUserId = new EditTextPreference(context); privateUserId.setTitle(str("revanced_sb_general_uuid")); privateUserId.setSummary(str("revanced_sb_general_uuid_sum")); privateUserId.setOnPreferenceChangeListener((preference1, newValue) -> { String newUUID = newValue.toString(); if (!SponsorBlockSettings.isValidSBUserId(newUUID)) { Utils.showToastLong(str("revanced_sb_general_uuid_invalid")); return false; } Settings.SB_PRIVATE_USER_ID.save(newUUID); updateUI(); fetchAndDisplayStats(); return true; }); category.addPreference(privateUserId); apiUrl = new Preference(context); apiUrl.setTitle(str("revanced_sb_general_api_url")); apiUrl.setSummary(Html.fromHtml(str("revanced_sb_general_api_url_sum"))); apiUrl.setOnPreferenceClickListener(preference1 -> { EditText editText = new EditText(context); editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI); editText.setText(Settings.SB_API_URL.get()); DialogInterface.OnClickListener urlChangeListener = (dialog, buttonPressed) -> { if (buttonPressed == DialogInterface.BUTTON_NEUTRAL) { Settings.SB_API_URL.resetToDefault(); Utils.showToastLong(str("revanced_sb_api_url_reset")); } else if (buttonPressed == DialogInterface.BUTTON_POSITIVE) { String serverAddress = editText.getText().toString(); if (!SponsorBlockSettings.isValidSBServerAddress(serverAddress)) { Utils.showToastLong(str("revanced_sb_api_url_invalid")); } else if (!serverAddress.equals(Settings.SB_API_URL.get())) { Settings.SB_API_URL.save(serverAddress); Utils.showToastLong(str("revanced_sb_api_url_changed")); } } }; new AlertDialog.Builder(context) .setTitle(apiUrl.getTitle()) .setView(editText) .setNegativeButton(android.R.string.cancel, null) .setNeutralButton(str("revanced_sb_reset"), urlChangeListener) .setPositiveButton(android.R.string.ok, urlChangeListener) .show(); return true; }); category.addPreference(apiUrl); importExport = new EditTextPreference(context) { protected void onPrepareDialogBuilder(AlertDialog.Builder builder) { builder.setNeutralButton(str("revanced_sb_settings_copy"), (dialog, which) -> { Utils.setClipboard(getEditText().getText().toString()); }); } }; importExport.setTitle(str("revanced_sb_settings_ie")); // Summary is set in updateUI() importExport.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { importExport.getEditText().setAutofillHints((String) null); } importExport.getEditText().setTextSize(TypedValue.COMPLEX_UNIT_PT, 8); importExport.setOnPreferenceClickListener(preference1 -> { importExport.getEditText().setText(SponsorBlockSettings.exportDesktopSettings()); return true; }); importExport.setOnPreferenceChangeListener((preference1, newValue) -> { SponsorBlockSettings.importDesktopSettings((String) newValue); updateSegmentCategories(); fetchAndDisplayStats(); updateUI(); return true; }); category.addPreference(importExport); } private void updateSegmentCategories() { try { segmentCategory.removeAll(); Activity activity = getActivity(); for (SegmentCategory category : SegmentCategory.categoriesWithoutUnsubmitted()) { segmentCategory.addPreference(new SegmentCategoryListPreference(activity, category)); } } catch (Exception ex) { Logger.printException(() -> "updateSegmentCategories failure", ex); } } private void addAboutCategory(Context context, PreferenceScreen screen) { PreferenceCategory category = new PreferenceCategory(context); screen.addPreference(category); category.setTitle(str("revanced_sb_about")); { Preference preference = new Preference(context); category.addPreference(preference); preference.setTitle(str("revanced_sb_about_api")); preference.setSummary(str("revanced_sb_about_api_sum")); preference.setOnPreferenceClickListener(preference1 -> { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://sponsor.ajay.app")); preference1.getContext().startActivity(i); return false; }); } } private void openGuidelines() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://wiki.sponsor.ajay.app/w/Guidelines")); getActivity().startActivity(intent); } private void fetchAndDisplayStats() { try { statsCategory.removeAll(); if (!SponsorBlockSettings.userHasSBPrivateId()) { // User has never voted or created any segments. No stats to show. addLocalUserStats(); return; } Preference loadingPlaceholderPreference = new Preference(this.getActivity()); loadingPlaceholderPreference.setEnabled(false); statsCategory.addPreference(loadingPlaceholderPreference); if (Settings.SB_ENABLED.get()) { loadingPlaceholderPreference.setTitle(str("revanced_sb_stats_loading")); Utils.runOnBackgroundThread(() -> { UserStats stats = SBRequester.retrieveUserStats(); Utils.runOnMainThread(() -> { // get back on main thread to modify UI elements addUserStats(loadingPlaceholderPreference, stats); addLocalUserStats(); }); }); } else { loadingPlaceholderPreference.setTitle(str("revanced_sb_stats_sb_disabled")); } } catch (Exception ex) { Logger.printException(() -> "fetchAndDisplayStats failure", ex); } } private void addUserStats(@NonNull Preference loadingPlaceholder, @Nullable UserStats stats) { Utils.verifyOnMainThread(); try { if (stats == null) { loadingPlaceholder.setTitle(str("revanced_sb_stats_connection_failure")); return; } statsCategory.removeAll(); Context context = statsCategory.getContext(); if (stats.totalSegmentCountIncludingIgnored > 0) { // If user has not created any segments, there's no reason to set a username. EditTextPreference preference = new EditTextPreference(context); statsCategory.addPreference(preference); String userName = stats.userName; preference.setTitle(fromHtml(str("revanced_sb_stats_username", userName))); preference.setSummary(str("revanced_sb_stats_username_change")); preference.setText(userName); preference.setOnPreferenceChangeListener((preference1, value) -> { Utils.runOnBackgroundThread(() -> { String newUserName = (String) value; String errorMessage = SBRequester.setUsername(newUserName); Utils.runOnMainThread(() -> { if (errorMessage == null) { preference.setTitle(fromHtml(str("revanced_sb_stats_username", newUserName))); preference.setText(newUserName); Utils.showToastLong(str("revanced_sb_stats_username_changed")); } else { preference.setText(userName); // revert to previous Utils.showToastLong(errorMessage); } }); }); return true; }); } { // number of segment submissions (does not include ignored segments) Preference preference = new Preference(context); statsCategory.addPreference(preference); String formatted = SponsorBlockUtils.getNumberOfSkipsString(stats.segmentCount); preference.setTitle(fromHtml(str("revanced_sb_stats_submissions", formatted))); if (stats.totalSegmentCountIncludingIgnored == 0) { preference.setSelectable(false); } else { preference.setOnPreferenceClickListener(preference1 -> { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://sb.ltn.fi/userid/" + stats.publicUserId)); preference1.getContext().startActivity(i); return true; }); } } { // "user reputation". Usually not useful, since it appears most users have zero reputation. // But if there is a reputation, then show it here Preference preference = new Preference(context); preference.setTitle(fromHtml(str("revanced_sb_stats_reputation", stats.reputation))); preference.setSelectable(false); if (stats.reputation != 0) { statsCategory.addPreference(preference); } } { // time saved for other users Preference preference = new Preference(context); statsCategory.addPreference(preference); String stats_saved; String stats_saved_sum; if (stats.totalSegmentCountIncludingIgnored == 0) { stats_saved = str("revanced_sb_stats_saved_zero"); stats_saved_sum = str("revanced_sb_stats_saved_sum_zero"); } else { stats_saved = str("revanced_sb_stats_saved", SponsorBlockUtils.getNumberOfSkipsString(stats.viewCount)); stats_saved_sum = str("revanced_sb_stats_saved_sum", SponsorBlockUtils.getTimeSavedString((long) (60 * stats.minutesSaved))); } preference.setTitle(fromHtml(stats_saved)); preference.setSummary(fromHtml(stats_saved_sum)); preference.setOnPreferenceClickListener(preference1 -> { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://sponsor.ajay.app/stats/")); preference1.getContext().startActivity(i); return false; }); } } catch (Exception ex) { Logger.printException(() -> "addUserStats failure", ex); } } private void addLocalUserStats() { // time the user saved by using SB Preference preference = new Preference(statsCategory.getContext()); statsCategory.addPreference(preference); Runnable updateStatsSelfSaved = () -> { String formatted = SponsorBlockUtils.getNumberOfSkipsString(Settings.SB_LOCAL_TIME_SAVED_NUMBER_SEGMENTS.get()); preference.setTitle(fromHtml(str("revanced_sb_stats_self_saved", formatted))); String formattedSaved = SponsorBlockUtils.getTimeSavedString(Settings.SB_LOCAL_TIME_SAVED_MILLISECONDS.get() / 1000); preference.setSummary(fromHtml(str("revanced_sb_stats_self_saved_sum", formattedSaved))); }; updateStatsSelfSaved.run(); preference.setOnPreferenceClickListener(preference1 -> { new AlertDialog.Builder(preference1.getContext()) .setTitle(str("revanced_sb_stats_self_saved_reset_title")) .setPositiveButton(android.R.string.yes, (dialog, whichButton) -> { Settings.SB_LOCAL_TIME_SAVED_NUMBER_SEGMENTS.resetToDefault(); Settings.SB_LOCAL_TIME_SAVED_MILLISECONDS.resetToDefault(); updateStatsSelfSaved.run(); }) .setNegativeButton(android.R.string.no, null).show(); return true; }); } }
28,142
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
NavigationBar.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/shared/NavigationBar.java
package app.revanced.integrations.youtube.shared; import static app.revanced.integrations.youtube.shared.NavigationBar.NavigationButton.CREATE; import android.app.Activity; import android.view.View; import androidx.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.shared.settings.BaseSettings; import app.revanced.integrations.youtube.settings.Settings; @SuppressWarnings("unused") public final class NavigationBar { // // Search bar // private static volatile WeakReference<View> searchBarResultsRef = new WeakReference<>(null); /** * Injection point. */ public static void searchBarResultsViewLoaded(View searchbarResults) { searchBarResultsRef = new WeakReference<>(searchbarResults); } /** * @return If the search bar is on screen. This includes if the player * is on screen and the search results are behind the player (and not visible). * Detecting the search is covered by the player can be done by checking {@link PlayerType#isMaximizedOrFullscreen()}. */ public static boolean isSearchBarActive() { View searchbarResults = searchBarResultsRef.get(); return searchbarResults != null && searchbarResults.getParent() != null; } // // Navigation bar buttons // /** * How long to wait for the set nav button latch to be released. Maximum wait time must * be as small as possible while still allowing enough time for the nav bar to update. * * YT calls it's back button handlers out of order, * and litho starts filtering before the navigation bar is updated. * * Fixing this situation and not needlessly waiting requires somehow * detecting if a back button key-press will cause a tab change. * * Typically after pressing the back button, the time between the first litho event and * when the nav button is updated is about 10-20ms. Using 50-100ms here should be enough time * and not noticeable, since YT typically takes 100-200ms (or more) to update the view anyways. * * This issue can also be avoided on a patch by patch basis, by avoiding calls to * {@link NavigationButton#getSelectedNavigationButton()} unless absolutely necessary. */ private static final long LATCH_AWAIT_TIMEOUT_MILLISECONDS = 75; /** * Used as a workaround to fix the issue of YT calling back button handlers out of order. * Used to hold calls to {@link NavigationButton#getSelectedNavigationButton()} * until the current navigation button can be determined. * * Only used when the hardware back button is pressed. */ @Nullable private static volatile CountDownLatch navButtonLatch; /** * Map of nav button layout views to Enum type. * No synchronization is needed, and this is always accessed from the main thread. */ private static final Map<View, NavigationButton> viewToButtonMap = new WeakHashMap<>(); static { // On app startup litho can start before the navigation bar is initialized. // Force it to wait until the nav bar is updated. createNavButtonLatch(); } private static void createNavButtonLatch() { navButtonLatch = new CountDownLatch(1); } private static void releaseNavButtonLatch() { CountDownLatch latch = navButtonLatch; if (latch != null) { navButtonLatch = null; latch.countDown(); } } private static void waitForNavButtonLatchIfNeeded() { CountDownLatch latch = navButtonLatch; if (latch == null) { return; } if (Utils.isCurrentlyOnMainThread()) { // The latch is released from the main thread, and waiting from the main thread will always timeout. // This situation has only been observed when navigating out of a submenu and not changing tabs. // and for that use case the nav bar does not change so it's safe to return here. Logger.printDebug(() -> "Cannot block main thread waiting for nav button. Using last known navbar button status."); return; } try { Logger.printDebug(() -> "Latch wait started"); if (latch.await(LATCH_AWAIT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS)) { // Back button changed the navigation tab. Logger.printDebug(() -> "Latch wait complete"); return; } // Timeout occurred, and a normal event when pressing the physical back button // does not change navigation tabs. releaseNavButtonLatch(); // Prevent other threads from waiting for no reason. Logger.printDebug(() -> "Latch wait timed out"); } catch (InterruptedException ex) { Logger.printException(() -> "Latch wait interrupted failure", ex); // Will never happen. } } /** * Last YT navigation enum loaded. Not necessarily the active navigation tab. * Always accessed from the main thread. */ @Nullable private static String lastYTNavigationEnumName; /** * Injection point. */ public static void setLastAppNavigationEnum(@Nullable Enum<?> ytNavigationEnumName) { if (ytNavigationEnumName != null) { lastYTNavigationEnumName = ytNavigationEnumName.name(); } } /** * Injection point. */ public static void navigationTabLoaded(final View navigationButtonGroup) { try { String lastEnumName = lastYTNavigationEnumName; for (NavigationButton button : NavigationButton.values()) { if (button.ytEnumName.equals(lastEnumName)) { Logger.printDebug(() -> "navigationTabLoaded: " + lastEnumName); viewToButtonMap.put(navigationButtonGroup, button); navigationTabCreatedCallback(button, navigationButtonGroup); return; } } // Log the unknown tab as exception level, only if debug is enabled. // This is because unknown tabs do no harm, and it's only relevant to developers. if (Settings.DEBUG.get()) { Logger.printException(() -> "Unknown tab: " + lastEnumName + " view: " + navigationButtonGroup.getClass()); } } catch (Exception ex) { Logger.printException(() -> "navigationTabLoaded failure", ex); } } /** * Injection point. * * Unique hook just for the 'Create' and 'You' tab. */ public static void navigationImageResourceTabLoaded(View view) { // 'You' tab has no YT enum name and the enum hook is not called for it. // Compare the last enum to figure out which tab this actually is. if (CREATE.ytEnumName.equals(lastYTNavigationEnumName)) { navigationTabLoaded(view); } else { lastYTNavigationEnumName = NavigationButton.LIBRARY_YOU.ytEnumName; navigationTabLoaded(view); } } /** * Injection point. */ public static void navigationTabSelected(View navButtonImageView, boolean isSelected) { try { if (!isSelected) { return; } NavigationButton button = viewToButtonMap.get(navButtonImageView); if (button == null) { // An unknown tab was selected. // Show a toast only if debug mode is enabled. if (BaseSettings.DEBUG.get()) { Logger.printException(() -> "Unknown navigation view selected: " + navButtonImageView); } NavigationButton.selectedNavigationButton = null; return; } NavigationButton.selectedNavigationButton = button; Logger.printDebug(() -> "Changed to navigation button: " + button); // Release any threads waiting for the selected nav button. releaseNavButtonLatch(); } catch (Exception ex) { Logger.printException(() -> "navigationTabSelected failure", ex); } } /** * Injection point. */ public static void onBackPressed(Activity activity) { Logger.printDebug(() -> "Back button pressed"); createNavButtonLatch(); } /** @noinspection EmptyMethod*/ private static void navigationTabCreatedCallback(NavigationButton button, View tabView) { // Code is added during patching. } public enum NavigationButton { HOME("PIVOT_HOME"), SHORTS("TAB_SHORTS"), /** * Create new video tab. * This tab will never be in a selected state, even if the create video UI is on screen. */ CREATE("CREATION_TAB_LARGE"), SUBSCRIPTIONS("PIVOT_SUBSCRIPTIONS"), /** * Notifications tab. Only present when * {@link Settings#SWITCH_CREATE_WITH_NOTIFICATIONS_BUTTON} is active. */ NOTIFICATIONS("TAB_ACTIVITY"), /** * Library tab when the user is not logged in. */ LIBRARY_LOGGED_OUT("ACCOUNT_CIRCLE"), /** * User is logged in with incognito mode enabled. */ LIBRARY_INCOGNITO("INCOGNITO_CIRCLE"), /** * Old library tab (pre 'You' layout), only present when version spoofing. */ LIBRARY_OLD_UI("VIDEO_LIBRARY_WHITE"), /** * 'You' library tab that is sometimes momentarily loaded. * When this is loaded, {@link #LIBRARY_YOU} is also present. * * This might be a temporary tab while the user profile photo is loading, * but its exact purpose is not entirely clear. */ LIBRARY_PIVOT_UNKNOWN("PIVOT_LIBRARY"), /** * Modern library tab with 'You' layout. */ // The hooked YT code does not use an enum, and a dummy name is used here. LIBRARY_YOU("YOU_LIBRARY_DUMMY_PLACEHOLDER_NAME"); @Nullable private static volatile NavigationButton selectedNavigationButton; /** * This will return null only if the currently selected tab is unknown. * This scenario will only happen if the UI has different tabs due to an A/B user test * or YT abruptly changes the navigation layout for some other reason. * * All code calling this method should handle a null return value. * * <b>Due to issues with how YT processes physical back button events, * this patch uses workarounds that can cause this method to take up to 75ms * if the device back button was recently pressed.</b> * * @return The active navigation tab. * If the user is in the upload video UI, this returns tab that is still visually * selected on screen (whatever tab the user was on before tapping the upload button). */ @Nullable public static NavigationButton getSelectedNavigationButton() { waitForNavButtonLatchIfNeeded(); return selectedNavigationButton; } /** * YouTube enum name for this tab. */ private final String ytEnumName; NavigationButton(String ytEnumName) { this.ytEnumName = ytEnumName; } public boolean isLibraryOrYouTab() { return this == LIBRARY_YOU || this == LIBRARY_PIVOT_UNKNOWN || this == LIBRARY_OLD_UI || this == LIBRARY_INCOGNITO || this == LIBRARY_LOGGED_OUT; } } }
11,982
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
BottomControlButton.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/videoplayer/BottomControlButton.java
package app.revanced.integrations.youtube.videoplayer; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.Objects; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.shared.settings.BooleanSetting; public abstract class BottomControlButton { private static final Animation fadeIn; private static final Animation fadeOut; private final WeakReference<ImageView> buttonRef; private final BooleanSetting setting; protected boolean isVisible; static { // TODO: check if these durations are correct. fadeIn = Utils.getResourceAnimation("fade_in"); fadeIn.setDuration(Utils.getResourceInteger("fade_duration_fast")); fadeOut = Utils.getResourceAnimation("fade_out"); fadeOut.setDuration(Utils.getResourceInteger("fade_duration_scheduled")); } @NonNull public static Animation getButtonFadeIn() { return fadeIn; } @NonNull public static Animation getButtonFadeOut() { return fadeOut; } public BottomControlButton(@NonNull ViewGroup bottomControlsViewGroup, @NonNull String imageViewButtonId, @NonNull BooleanSetting booleanSetting, @NonNull View.OnClickListener onClickListener, @Nullable View.OnLongClickListener longClickListener) { Logger.printDebug(() -> "Initializing button: " + imageViewButtonId); setting = booleanSetting; // Create the button. ImageView imageView = Objects.requireNonNull(bottomControlsViewGroup.findViewById( Utils.getResourceIdentifier(imageViewButtonId, "id") )); imageView.setOnClickListener(onClickListener); if (longClickListener != null) { imageView.setOnLongClickListener(longClickListener); } imageView.setVisibility(View.GONE); buttonRef = new WeakReference<>(imageView); } public void setVisibility(boolean visible) { if (isVisible == visible) return; isVisible = visible; ImageView imageView = buttonRef.get(); if (imageView == null) { return; } imageView.clearAnimation(); if (visible && setting.get()) { imageView.startAnimation(fadeIn); imageView.setVisibility(View.VISIBLE); } else if (imageView.getVisibility() == View.VISIBLE) { imageView.startAnimation(fadeOut); imageView.setVisibility(View.GONE); } } }
2,768
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ExternalDownloadButton.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/videoplayer/ExternalDownloadButton.java
package app.revanced.integrations.youtube.videoplayer; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.youtube.patches.DownloadsPatch; import app.revanced.integrations.youtube.patches.VideoInformation; import app.revanced.integrations.youtube.settings.Settings; @SuppressWarnings("unused") public class ExternalDownloadButton extends BottomControlButton { @Nullable private static ExternalDownloadButton instance; public ExternalDownloadButton(ViewGroup viewGroup) { super( viewGroup, "revanced_external_download_button", Settings.EXTERNAL_DOWNLOADER, ExternalDownloadButton::onDownloadClick, null ); } /** * Injection point. */ public static void initializeButton(View view) { try { instance = new ExternalDownloadButton((ViewGroup) view); } catch (Exception ex) { Logger.printException(() -> "initializeButton failure", ex); } } /** * Injection point. */ public static void changeVisibility(boolean showing) { if (instance != null) instance.setVisibility(showing); } private static void onDownloadClick(View view) { DownloadsPatch.launchExternalDownloader( VideoInformation.getVideoId(), view.getContext(), true); } }
1,532
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
CopyVideoUrlButton.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/videoplayer/CopyVideoUrlButton.java
package app.revanced.integrations.youtube.videoplayer; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import app.revanced.integrations.youtube.patches.CopyVideoUrlPatch; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.shared.Logger; public class CopyVideoUrlButton extends BottomControlButton { @Nullable private static CopyVideoUrlButton instance; public CopyVideoUrlButton(ViewGroup viewGroup) { super( viewGroup, "revanced_copy_video_url_button", Settings.COPY_VIDEO_URL, view -> CopyVideoUrlPatch.copyUrl(false), view -> { CopyVideoUrlPatch.copyUrl(true); return true; } ); } /** * Injection point. */ public static void initializeButton(View view) { try { instance = new CopyVideoUrlButton((ViewGroup) view); } catch (Exception ex) { Logger.printException(() -> "initializeButton failure", ex); } } /** * Injection point. */ public static void changeVisibility(boolean showing) { if (instance != null) instance.setVisibility(showing); } }
1,310
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
CopyVideoUrlTimestampButton.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/videoplayer/CopyVideoUrlTimestampButton.java
package app.revanced.integrations.youtube.videoplayer; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import app.revanced.integrations.youtube.patches.CopyVideoUrlPatch; import app.revanced.integrations.youtube.settings.Settings; import app.revanced.integrations.shared.Logger; public class CopyVideoUrlTimestampButton extends BottomControlButton { @Nullable private static CopyVideoUrlTimestampButton instance; public CopyVideoUrlTimestampButton(ViewGroup bottomControlsViewGroup) { super( bottomControlsViewGroup, "revanced_copy_video_url_timestamp_button", Settings.COPY_VIDEO_URL_TIMESTAMP, view -> CopyVideoUrlPatch.copyUrl(true), view -> { CopyVideoUrlPatch.copyUrl(false); return true; } ); } /** * Injection point. */ public static void initializeButton(View bottomControlsViewGroup) { try { instance = new CopyVideoUrlTimestampButton((ViewGroup) bottomControlsViewGroup); } catch (Exception ex) { Logger.printException(() -> "initializeButton failure", ex); } } /** * Injection point. */ public static void changeVisibility(boolean showing) { if (instance != null) instance.setVisibility(showing); } }
1,433
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
Route.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/requests/Route.java
package app.revanced.integrations.youtube.requests; public class Route { private final String route; private final Method method; private final int paramCount; public Route(Method method, String route) { this.method = method; this.route = route; this.paramCount = countMatches(route, '{'); if (paramCount != countMatches(route, '}')) throw new IllegalArgumentException("Not enough parameters"); } public Method getMethod() { return method; } public CompiledRoute compile(String... params) { if (params.length != paramCount) throw new IllegalArgumentException("Error compiling route [" + route + "], incorrect amount of parameters provided. " + "Expected: " + paramCount + ", provided: " + params.length); StringBuilder compiledRoute = new StringBuilder(route); for (int i = 0; i < paramCount; i++) { int paramStart = compiledRoute.indexOf("{"); int paramEnd = compiledRoute.indexOf("}"); compiledRoute.replace(paramStart, paramEnd + 1, params[i]); } return new CompiledRoute(this, compiledRoute.toString()); } public static class CompiledRoute { private final Route baseRoute; private final String compiledRoute; private CompiledRoute(Route baseRoute, String compiledRoute) { this.baseRoute = baseRoute; this.compiledRoute = compiledRoute; } public String getCompiledRoute() { return compiledRoute; } public Method getMethod() { return baseRoute.method; } } private int countMatches(CharSequence seq, char c) { int count = 0; for (int i = 0; i < seq.length(); i++) { if (seq.charAt(i) == c) count++; } return count; } public enum Method { GET, POST } }
1,972
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
Requester.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/youtube/requests/Requester.java
package app.revanced.integrations.youtube.requests; import app.revanced.integrations.shared.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class Requester { private Requester() { } public static HttpURLConnection getConnectionFromRoute(String apiUrl, Route route, String... params) throws IOException { return getConnectionFromCompiledRoute(apiUrl, route.compile(params)); } public static HttpURLConnection getConnectionFromCompiledRoute(String apiUrl, Route.CompiledRoute route) throws IOException { String url = apiUrl + route.getCompiledRoute(); HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod(route.getMethod().name()); String agentString = System.getProperty("http.agent") + "; ReVanced/" + Utils.getAppVersionName() + " (" + Utils.getPatchesReleaseVersion() + ")"; connection.setRequestProperty("User-Agent", agentString); return connection; } /** * Parse the {@link HttpURLConnection}, and closes the underlying InputStream. */ private static String parseInputStreamAndClose(InputStream inputStream) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { StringBuilder jsonBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { jsonBuilder.append(line); jsonBuilder.append("\n"); } return jsonBuilder.toString(); } } /** * Parse the {@link HttpURLConnection} response as a String. * This does not close the url connection. If further requests to this host are unlikely * in the near future, then instead use {@link #parseStringAndDisconnect(HttpURLConnection)}. */ public static String parseString(HttpURLConnection connection) throws IOException { return parseInputStreamAndClose(connection.getInputStream()); } /** * Parse the {@link HttpURLConnection} response as a String, and disconnect. * * <b>Should only be used if other requests to the server in the near future are unlikely</b> * * @see #parseString(HttpURLConnection) */ public static String parseStringAndDisconnect(HttpURLConnection connection) throws IOException { String result = parseString(connection); connection.disconnect(); return result; } /** * Parse the {@link HttpURLConnection} error stream as a String. * If the server sent no error response data, this returns an empty string. */ public static String parseErrorString(HttpURLConnection connection) throws IOException { InputStream errorStream = connection.getErrorStream(); if (errorStream == null) { return ""; } return parseInputStreamAndClose(errorStream); } /** * Parse the {@link HttpURLConnection} error stream as a String, and disconnect. * If the server sent no error response data, this returns an empty string. * * Should only be used if other requests to the server are unlikely in the near future. * * @see #parseErrorString(HttpURLConnection) */ public static String parseErrorStringAndDisconnect(HttpURLConnection connection) throws IOException { String result = parseErrorString(connection); connection.disconnect(); return result; } /** * Parse the {@link HttpURLConnection} response into a JSONObject. * This does not close the url connection. If further requests to this host are unlikely * in the near future, then instead use {@link #parseJSONObjectAndDisconnect(HttpURLConnection)}. */ public static JSONObject parseJSONObject(HttpURLConnection connection) throws JSONException, IOException { return new JSONObject(parseString(connection)); } /** * Parse the {@link HttpURLConnection}, close the underlying InputStream, and disconnect. * * <b>Should only be used if other requests to the server in the near future are unlikely</b> * * @see #parseJSONObject(HttpURLConnection) */ public static JSONObject parseJSONObjectAndDisconnect(HttpURLConnection connection) throws JSONException, IOException { JSONObject object = parseJSONObject(connection); connection.disconnect(); return object; } /** * Parse the {@link HttpURLConnection}, and closes the underlying InputStream. * This does not close the url connection. If further requests to this host are unlikely * in the near future, then instead use {@link #parseJSONArrayAndDisconnect(HttpURLConnection)}. */ public static JSONArray parseJSONArray(HttpURLConnection connection) throws JSONException, IOException { return new JSONArray(parseString(connection)); } /** * Parse the {@link HttpURLConnection}, close the underlying InputStream, and disconnect. * * <b>Should only be used if other requests to the server in the near future are unlikely</b> * * @see #parseJSONArray(HttpURLConnection) */ public static JSONArray parseJSONArrayAndDisconnect(HttpURLConnection connection) throws JSONException, IOException { JSONArray array = parseJSONArray(connection); connection.disconnect(); return array; } }
5,709
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
StringRef.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/StringRef.java
package app.revanced.integrations.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; } }
3,639
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
Logger.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/Logger.java
package app.revanced.integrations.shared; import static app.revanced.integrations.shared.settings.BaseSettings.DEBUG; import static app.revanced.integrations.shared.settings.BaseSettings.DEBUG_STACKTRACE; import static app.revanced.integrations.shared.settings.BaseSettings.DEBUG_TOAST_ON_ERROR; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.io.PrintWriter; import java.io.StringWriter; import app.revanced.integrations.shared.settings.BaseSettings; public class Logger { /** * Log messages using lambdas. */ 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) { if (DEBUG.get()) { var messageString = message.buildMessageString(); if (DEBUG_STACKTRACE.get()) { var builder = new StringBuilder(messageString); var sw = new StringWriter(); new Throwable().printStackTrace(new PrintWriter(sw)); builder.append('\n').append(sw); messageString = builder.toString(); } Log.d(REVANCED_LOG_PREFIX + message.findOuterClassSimpleName(), messageString); } } /** * 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); } }
6,093
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
Utils.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/Utils.java
package app.revanced.integrations.shared; import android.annotation.SuppressLint; 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.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.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.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.integrations.shared.settings.BooleanSetting; import app.revanced.integrations.shared.settings.preference.ReVancedAboutPreference; import kotlin.text.Regex; 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. */ public static String getPatchesReleaseVersion() { return ""; // Value is replaced during patching. } /** * @return The version name of the app, such as "YouTube". */ 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 hideViewBy1dpUnderCondition(BooleanSetting condition, View view) { if (!condition.get()) return; Logger.printDebug(() -> "Hiding view with setting: " + condition); hideViewByLayoutParams(view); } /** * 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 (!condition.get()) return; Logger.printDebug(() -> "Hiding view with setting: " + condition); view.setVisibility(View.GONE); } /** * 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); } /** * @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; } 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; } /** * 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 1x1 * @param view The view to hide. */ public static void hideViewByLayoutParams(View view) { if (view instanceof LinearLayout) { LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(1, 1); view.setLayoutParams(layoutParams); } else if (view instanceof FrameLayout) { FrameLayout.LayoutParams layoutParams2 = new FrameLayout.LayoutParams(1, 1); view.setLayoutParams(layoutParams2); } else if (view instanceof RelativeLayout) { RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(1, 1); view.setLayoutParams(layoutParams3); } else if (view instanceof Toolbar) { Toolbar.LayoutParams layoutParams4 = new Toolbar.LayoutParams(1, 1); view.setLayoutParams(layoutParams4); } else if (view instanceof ViewGroup) { ViewGroup.LayoutParams layoutParams5 = new ViewGroup.LayoutParams(1, 1); view.setLayoutParams(layoutParams5); } else { Logger.printDebug(() -> "Hidden view with id " + view.getId()); } } /** * {@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 Regex punctuationRegex = new Regex("\\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 punctuationRegex.replace(original, "").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); } } }
20,575
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
GmsCoreSupport.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/GmsCoreSupport.java
package app.revanced.integrations.shared; import static app.revanced.integrations.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 { 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) { // Use a delay to allow the activity to finish initializing. // Otherwise, if device is in dark mode the dialog is shown with wrong color scheme. Utils.runOnMainThreadDelayed(() -> { new AlertDialog.Builder(context) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle(str("gms_core_dialog_title")) .setMessage(str(dialogMessageRef)) .setPositiveButton(str(positiveButtonStringRef), onPositiveClickListener) // Allow using back button to skip the action, just in case the check can never be satisfied. .setCancelable(true) .show(); }, 100); } /** * Injection point. */ @RequiresApi(api = Build.VERSION_CODES.N) public static void checkGmsCore(Activity context) { try { // 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"; } }
6,186
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
EnumSetting.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/EnumSetting.java
package app.revanced.integrations.shared.settings; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import app.revanced.integrations.shared.Logger; import org.json.JSONException; import org.json.JSONObject; import java.util.Locale; import java.util.Objects; /** * 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; } }
4,002
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
BaseSettings.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/BaseSettings.java
package app.revanced.integrations.shared.settings; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static app.revanced.integrations.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"); }
808
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
StringSetting.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/StringSetting.java
package app.revanced.integrations.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; } }
2,636
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
LongSetting.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/LongSetting.java
package app.revanced.integrations.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; } }
2,610
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
IntegerSetting.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/IntegerSetting.java
package app.revanced.integrations.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; } }
2,687
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
FloatSetting.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/FloatSetting.java
package app.revanced.integrations.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; } }
2,646
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
Setting.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/Setting.java
package app.revanced.integrations.shared.settings; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.StringRef; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.shared.settings.preference.SharedPrefCategory; import app.revanced.integrations.youtube.sponsorblock.SponsorBlockSettings; import org.jetbrains.annotations.NotNull; import org.json.JSONException; import org.json.JSONObject; import java.util.*; import static app.revanced.integrations.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 integrations 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.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 }
16,505
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
BooleanSetting.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/BooleanSetting.java
package app.revanced.integrations.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; } }
3,114
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ImportExportPreference.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/preference/ImportExportPreference.java
package app.revanced.integrations.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.integrations.shared.settings.Setting; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import static app.revanced.integrations.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 { // 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; } } }
3,645
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ResettableEditTextPreference.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/preference/ResettableEditTextPreference.java
package app.revanced.integrations.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.integrations.shared.settings.Setting; import app.revanced.integrations.shared.Logger; import java.util.Objects; import static app.revanced.integrations.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); 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); } }); } }
2,366
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
SharedPrefCategory.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/preference/SharedPrefCategory.java
package app.revanced.integrations.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.integrations.shared.Logger; import app.revanced.integrations.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; } }
6,534
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ReVancedAboutPreference.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/preference/ReVancedAboutPreference.java
package app.revanced.integrations.shared.settings.preference; import static app.revanced.integrations.shared.StringRef.str; import static app.revanced.integrations.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.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.youtube.requests.Requester; import app.revanced.integrations.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;"); // #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(ReVancedSocialLink[] 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 (ReVancedSocialLink 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) { ReVancedSocialLink[] 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 ReVancedSocialLink { final boolean preferred; final String name; final String url; ReVancedSocialLink(JSONObject json) throws JSONException { this(json.getBoolean("preferred"), json.getString("name"), json.getString("url") ); } ReVancedSocialLink(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 { /** * Links to use if fetch links api call fails. */ private static final ReVancedSocialLink[] NO_CONNECTION_STATIC_LINKS = { new ReVancedSocialLink(true, "ReVanced.app", "https://revanced.app") }; 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 ReVancedSocialLink[] fetchedLinks; static boolean hasFetchedLinks() { return fetchedLinks != null; } static ReVancedSocialLink[] 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<ReVancedSocialLink> links = new ArrayList<>(); for (int i = 0, length = socials.length(); i < length; i++) { ReVancedSocialLink link = new ReVancedSocialLink(socials.getJSONObject(i)); links.add(link); } Logger.printDebug(() -> "links: " + links); return fetchedLinks = links.toArray(new ReVancedSocialLink[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; } }
11,605
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
AbstractPreferenceFragment.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/shared/settings/preference/AbstractPreferenceFragment.java
package app.revanced.integrations.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.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.shared.settings.BooleanSetting; import app.revanced.integrations.shared.settings.Setting; import static app.revanced.integrations.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); } } } } /** * 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(); } }
11,428
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
TimelineFilterPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tumblr/patches/TimelineFilterPatch.java
package app.revanced.integrations.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(); } } }
1,315
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
Utils.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/Utils.java
package app.revanced.integrations.tiktok; import app.revanced.integrations.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}; } }
840
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
AdsFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/feedfilter/AdsFilter.java
package app.revanced.integrations.tiktok.feedfilter; import app.revanced.integrations.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(); } }
433
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ViewCountFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/feedfilter/ViewCountFilter.java
package app.revanced.integrations.tiktok.feedfilter; import app.revanced.integrations.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.integrations.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; } }
900
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
LikeCountFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/feedfilter/LikeCountFilter.java
package app.revanced.integrations.tiktok.feedfilter; import app.revanced.integrations.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.integrations.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; } }
906
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ImageVideoFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/feedfilter/ImageVideoFilter.java
package app.revanced.integrations.tiktok.feedfilter; import app.revanced.integrations.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(); } }
432
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
LiveFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/feedfilter/LiveFilter.java
package app.revanced.integrations.tiktok.feedfilter; import app.revanced.integrations.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(); } }
425
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
StoryFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/feedfilter/StoryFilter.java
package app.revanced.integrations.tiktok.feedfilter; import app.revanced.integrations.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(); } }
414
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
IFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/feedfilter/IFilter.java
package app.revanced.integrations.tiktok.feedfilter; import com.ss.android.ugc.aweme.feed.model.Aweme; public interface IFilter { boolean getEnabled(); boolean getFiltered(Aweme item); }
198
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
FeedItemsFilter.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/feedfilter/FeedItemsFilter.java
package app.revanced.integrations.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; } } } } }
1,079
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
DownloadsPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/download/DownloadsPatch.java
package app.revanced.integrations.tiktok.download; import app.revanced.integrations.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(); } }
377
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
PlaybackSpeedPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/speed/PlaybackSpeedPatch.java
package app.revanced.integrations.tiktok.speed; import app.revanced.integrations.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(); } }
364
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
AdPersonalizationActivityHook.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/AdPersonalizationActivityHook.java
package app.revanced.integrations.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.integrations.shared.Logger; import app.revanced.integrations.shared.Utils; import app.revanced.integrations.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"); } } }
3,475
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
SettingsStatus.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/SettingsStatus.java
package app.revanced.integrations.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() { } }
526
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
Settings.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/Settings.java
package app.revanced.integrations.tiktok.settings; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import app.revanced.integrations.shared.settings.BaseSettings; import app.revanced.integrations.shared.settings.BooleanSetting; import app.revanced.integrations.shared.settings.FloatSetting; import app.revanced.integrations.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"); }
1,870
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
RangeValuePreference.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/preference/RangeValuePreference.java
package app.revanced.integrations.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.integrations.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); } } }
4,182
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ReVancedPreferenceFragment.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/preference/ReVancedPreferenceFragment.java
package app.revanced.integrations.tiktok.settings.preference; import android.preference.Preference; import android.preference.PreferenceScreen; import androidx.annotation.NonNull; import app.revanced.integrations.shared.settings.Setting; import app.revanced.integrations.shared.settings.preference.AbstractPreferenceFragment; import app.revanced.integrations.tiktok.settings.preference.categories.DownloadsPreferenceCategory; import app.revanced.integrations.tiktok.settings.preference.categories.FeedFilterPreferenceCategory; import app.revanced.integrations.tiktok.settings.preference.categories.IntegrationsPreferenceCategory; import app.revanced.integrations.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 integrations. 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 IntegrationsPreferenceCategory(context, preferenceScreen); } }
2,655
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
DownloadPathPreference.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/preference/DownloadPathPreference.java
package app.revanced.integrations.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.integrations.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; } }
4,517
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
TogglePreference.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/preference/TogglePreference.java
package app.revanced.integrations.tiktok.settings.preference; import android.content.Context; import android.preference.SwitchPreference; import app.revanced.integrations.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()); } }
567
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
InputTextPreference.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/preference/InputTextPreference.java
package app.revanced.integrations.tiktok.settings.preference; import android.content.Context; import android.preference.EditTextPreference; import app.revanced.integrations.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()); } }
540
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
ConditionalPreferenceCategory.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/preference/categories/ConditionalPreferenceCategory.java
package app.revanced.integrations.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); }
662
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
SimSpoofPreferenceCategory.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/preference/categories/SimSpoofPreferenceCategory.java
package app.revanced.integrations.tiktok.settings.preference.categories; import android.content.Context; import android.preference.PreferenceScreen; import app.revanced.integrations.tiktok.settings.Settings; import app.revanced.integrations.tiktok.settings.SettingsStatus; import app.revanced.integrations.tiktok.settings.preference.InputTextPreference; import app.revanced.integrations.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 )); } }
1,659
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
FeedFilterPreferenceCategory.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/preference/categories/FeedFilterPreferenceCategory.java
package app.revanced.integrations.tiktok.settings.preference.categories; import android.content.Context; import android.preference.PreferenceScreen; import app.revanced.integrations.tiktok.settings.preference.RangeValuePreference; import app.revanced.integrations.tiktok.settings.Settings; import app.revanced.integrations.tiktok.settings.SettingsStatus; import app.revanced.integrations.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 )); } }
2,023
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
IntegrationsPreferenceCategory.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/preference/categories/IntegrationsPreferenceCategory.java
package app.revanced.integrations.tiktok.settings.preference.categories; import android.content.Context; import android.preference.PreferenceScreen; import app.revanced.integrations.shared.settings.BaseSettings; import app.revanced.integrations.tiktok.settings.preference.TogglePreference; @SuppressWarnings("deprecation") public class IntegrationsPreferenceCategory extends ConditionalPreferenceCategory { public IntegrationsPreferenceCategory(Context context, PreferenceScreen screen) { super(context, screen); setTitle("Integrations"); } @Override public boolean getSettingsStatus() { return true; } @Override public void addPreferences(Context context) { addPreference(new TogglePreference(context, "Enable debug log", "Show integration debug log.", BaseSettings.DEBUG )); } }
906
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
DownloadsPreferenceCategory.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/settings/preference/categories/DownloadsPreferenceCategory.java
package app.revanced.integrations.tiktok.settings.preference.categories; import android.content.Context; import android.preference.PreferenceScreen; import app.revanced.integrations.tiktok.settings.Settings; import app.revanced.integrations.tiktok.settings.SettingsStatus; import app.revanced.integrations.tiktok.settings.preference.DownloadPathPreference; import app.revanced.integrations.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 )); } }
1,209
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
RememberClearDisplayPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/cleardisplay/RememberClearDisplayPatch.java
package app.revanced.integrations.tiktok.cleardisplay; import app.revanced.integrations.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); } }
411
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
SpoofSimPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/tiktok/spoof/sim/SpoofSimPatch.java
package app.revanced.integrations.tiktok.spoof.sim; import app.revanced.integrations.shared.Logger; import app.revanced.integrations.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; } }
1,183
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
FixSLinksPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/syncforreddit/FixSLinksPatch.java
package app.revanced.integrations.syncforreddit; import android.os.StrictMode; import app.revanced.integrations.shared.Logger; import java.net.HttpURLConnection; import java.net.URL; public final class FixSLinksPatch { public static String resolveSLink(String link) { if (link.matches(".*reddit\\.com/r/[^/]+/s/[^/]+")) { Logger.printInfo(() -> "Resolving " + link); try { URL url = new URL(link); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("HEAD"); // Disable strict mode in order to allow network access on the main thread. // This is not ideal, but it's the easiest solution for now. final var currentPolicy = StrictMode.getThreadPolicy(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); connection.connect(); String location = connection.getHeaderField("location"); connection.disconnect(); // Restore the original strict mode policy. StrictMode.setThreadPolicy(currentPolicy); Logger.printInfo(() -> "Resolved " + link + " -> " + location); return location; } catch (Exception e) { Logger.printException(() -> "Failed to resolve " + link, e); } } return link; } }
1,614
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
OpenLinksWithAppChooserPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitter/patches/links/OpenLinksWithAppChooserPatch.java
package app.revanced.integrations.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)); } }
484
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
Utils.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/Utils.java
package app.revanced.integrations.twitch; public class Utils { /* Called from SettingsPatch smali */ public static int getStringId(String name) { return app.revanced.integrations.shared.Utils.getResourceIdentifier(name, "string"); } /* Called from SettingsPatch smali */ public static int getDrawableId(String name) { return app.revanced.integrations.shared.Utils.getResourceIdentifier(name, "drawable"); } }
452
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
DebugModePatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/patches/DebugModePatch.java
package app.revanced.integrations.twitch.patches; import app.revanced.integrations.twitch.settings.Settings; @SuppressWarnings("unused") public class DebugModePatch { public static boolean isDebugModeEnabled() { return Settings.TWITCH_DEBUG_MODE.get(); } }
275
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
AutoClaimChannelPointsPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/patches/AutoClaimChannelPointsPatch.java
package app.revanced.integrations.twitch.patches; import app.revanced.integrations.twitch.settings.Settings; @SuppressWarnings("unused") public class AutoClaimChannelPointsPatch { public static boolean shouldAutoClaim() { return Settings.AUTO_CLAIM_CHANNEL_POINTS.get(); } }
293
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
AudioAdsPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/patches/AudioAdsPatch.java
package app.revanced.integrations.twitch.patches; import app.revanced.integrations.twitch.settings.Settings; @SuppressWarnings("unused") public class AudioAdsPatch { public static boolean shouldBlockAudioAds() { return Settings.BLOCK_AUDIO_ADS.get(); } }
273
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
EmbeddedAdsPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/patches/EmbeddedAdsPatch.java
package app.revanced.integrations.twitch.patches; import app.revanced.integrations.twitch.api.RequestInterceptor; @SuppressWarnings("unused") public class EmbeddedAdsPatch { public static RequestInterceptor createRequestInterceptor() { return new RequestInterceptor(); } }
290
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z
VideoAdsPatch.java
/FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/patches/VideoAdsPatch.java
package app.revanced.integrations.twitch.patches; import app.revanced.integrations.twitch.settings.Settings; @SuppressWarnings("unused") public class VideoAdsPatch { public static boolean shouldBlockVideoAds() { return Settings.BLOCK_VIDEO_ADS.get(); } }
272
Java
.java
ReVanced/revanced-integrations
649
221
10
2022-03-15T20:37:24Z
2024-05-08T22:30:33Z