Skip to content

Commit

Permalink
feat: Move strings to resources for localization (ReVanced#420)
Browse files Browse the repository at this point in the history
Co-authored-by: semantic-release-bot <semantic-release-bot@martynus.net>
Co-authored-by: oSumAtrIX <johan.melkonyan1@web.de>
  • Loading branch information
3 people committed Jan 27, 2024
1 parent e455262 commit 7ae10be
Show file tree
Hide file tree
Showing 32 changed files with 266 additions and 203 deletions.
44 changes: 44 additions & 0 deletions app/src/main/java/app/revanced/integrations/shared/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.preference.Preference;
import android.preference.PreferenceGroup;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
Expand All @@ -26,13 +28,16 @@
import java.text.Bidi;
import java.util.Locale;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
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 kotlin.text.Regex;

public class Utils {

Expand Down Expand Up @@ -388,6 +393,45 @@ public static void hideViewByLayoutParams(View view) {
}
}

private static final Regex punctuationRegex = new Regex("\\p{P}+");

/**
* Sort the preferences by title and ignore the casing.
*
* Android Preferences are automatically sorted by title,
* but if using a localized string key it sorts on the key and not the actual title text that's used at runtime.
*
* @param menuDepthToSort Maximum menu depth to sort. Menus deeper than this value
* will show preferences in the order created in patches.
*/
public static void sortPreferenceGroupByTitle(PreferenceGroup group, int menuDepthToSort) {
if (menuDepthToSort == 0) return;

SortedMap<String, Preference> preferences = new TreeMap<>();
for (int i = 0, prefCount = group.getPreferenceCount(); i < prefCount; i++) {
Preference preference = group.getPreference(i);
if (preference instanceof PreferenceGroup) {
sortPreferenceGroupByTitle((PreferenceGroup) preference, menuDepthToSort - 1);
}
preferences.put(removePunctuationConvertToLowercase(preference.getTitle()), preference);
}

int prefIndex = 0;
for (Preference pref : preferences.values()) {
int indexToSet = prefIndex++;
if (pref instanceof PreferenceGroup || pref.getIntent() != null) {
// Place preference groups last.
// Use an offset to push the group to the end.
indexToSet += 1000;
}
pref.setOrder(indexToSet);
}
}

public static String removePunctuationConvertToLowercase(CharSequence original) {
return punctuationRegex.replace(original, "").toLowerCase();
}

public enum NetworkType {
NONE,
MOBILE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ protected void initialize() {

if (identifier == 0) return;
addPreferencesFromResource(identifier);
Utils.sortPreferenceGroupByTitle(getPreferenceScreen(), 2);
}

private void showSettingUserDialogConfirmation(SwitchPreference switchPref, BooleanSetting setting) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@

@SuppressWarnings("unused")
public class ShowDeletedMessagesPatch {

/**
* Injection point.
*/
public static boolean shouldUseSpoiler() {
return "spoiler".equals(Settings.SHOW_DELETED_MESSAGES.get());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

@SuppressWarnings("unused")
public final class ChangeStartPagePatch {
public static void changeIntent(Intent intent) {
public static void changeIntent(final Intent intent) {
final var startPage = Settings.START_PAGE.get();
if (startPage.isEmpty()) return;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,16 @@ public static void checkAvailability() {
Logger.printInfo(() -> "GmsCore was not found", exception);
search(context, getGmsCoreDownloadLink(), str("gms_core_not_installed_warning"));

// Gracefully exit the app, so it does not crash.
System.exit(0);
}

try (var client = context.getContentResolver().acquireContentProviderClient(GMS_CORE_PROVIDER)) {
if (client != null) return;

Logger.printInfo(() -> "GmsCore is not running in the background");
search(context, DONT_KILL_MY_APP_LINK, str("gms_core_not_running_warning"));

System.exit(0);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Locale;
import java.util.UUID;

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")
Expand All @@ -39,17 +41,18 @@ public static void showAnnouncement(final Activity context) {

Utils.runOnBackgroundThread(() -> {
try {
HttpURLConnection connection = AnnouncementsRoutes.getAnnouncementsConnectionFromRoute(GET_LATEST_ANNOUNCEMENT, CONSUMER);
HttpURLConnection connection = AnnouncementsRoutes.getAnnouncementsConnectionFromRoute(
GET_LATEST_ANNOUNCEMENT, CONSUMER, Locale.getDefault().toLanguageTag());

Logger.printDebug(() -> "Get latest announcement route connection url: " + connection.getURL().toString());
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_HASH.get().isEmpty()) return;

Settings.ANNOUNCEMENT_LAST_HASH.resetToDefault();
Utils.showToastLong("Failed to get announcement");
Utils.showToastLong(str("revanced_announcements_connection_failed"));

return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@
public class AnnouncementsRoutes {
private static final String ANNOUNCEMENTS_PROVIDER = "https://api.revanced.app/v2";


public static final Route GET_LATEST_ANNOUNCEMENT = new Route(GET, "/announcements/youtube/latest?consumer={consumer}");
/**
* '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?consumer={consumer}&language={language}");

private AnnouncementsRoutes() {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
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")
Expand Down Expand Up @@ -43,13 +44,13 @@ private static void changeDefaultQuality(int defaultQuality) {
String networkTypeMessage;
if (Utils.getNetworkType() == NetworkType.MOBILE) {
mobileQualitySetting.save(defaultQuality);
networkTypeMessage = "mobile";
networkTypeMessage = str("revanced_remember_video_quality_mobile");
} else {
wifiQualitySetting.save(defaultQuality);
networkTypeMessage = "Wi-Fi";
networkTypeMessage = str("revanced_remember_video_quality_wifi");
}
Utils.showToastShort("Changed default " + networkTypeMessage
+ " quality to: " + defaultQuality +"p");
Utils.showToastShort(
str("revanced_remember_video_quality_toast", networkTypeMessage, (defaultQuality + "p")));
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
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;
Expand Down Expand Up @@ -62,16 +64,15 @@ private static void loadCustomSpeeds() {
throw new IllegalArgumentException();
}
if (speed >= MAXIMUM_PLAYBACK_SPEED) {
resetCustomSpeeds("Custom speeds must be less than " + MAXIMUM_PLAYBACK_SPEED
+ ". Using default values.");
resetCustomSpeeds(str("revanced_custom_playback_speeds_invalid", MAXIMUM_PLAYBACK_SPEED));
loadCustomSpeeds();
return;
}
customPlaybackSpeeds[i] = speed;
}
} catch (Exception ex) {
Logger.printInfo(() -> "parse error", ex);
resetCustomSpeeds("Invalid custom playback speeds. Using default values.");
resetCustomSpeeds(str("revanced_custom_playback_speeds_parse_exception"));
loadCustomSpeeds();
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
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;
Expand All @@ -25,7 +27,7 @@ public static void newVideoStarted(Object ignoredPlayerController) {
public static void userSelectedPlaybackSpeed(float playbackSpeed) {
if (Settings.REMEMBER_PLAYBACK_SPEED_LAST_SELECTED.get()) {
Settings.PLAYBACK_SPEED_DEFAULT.save(playbackSpeed);
Utils.showToastLong("Changed default speed to: " + playbackSpeed + "x");
Utils.showToastLong(str("revanced_remember_playback_speed_toast", (playbackSpeed + "x")));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
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.*;

public class StoryboardRendererRequester {
Expand Down Expand Up @@ -62,14 +63,14 @@ private static JSONObject fetchPlayerResponse(@NonNull String requestBody, boole
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("Spoof storyboard temporarily not available (API timed out)",
ex, showToastOnIOException);
handleConnectionError(str("revanced_spoof_storyboard_timeout"), ex, showToastOnIOException);
} catch (IOException ex) {
handleConnectionError("Spoof storyboard temporarily not available: " + ex.getMessage(),
handleConnectionError(str("revanced_spoof_storyboard_io_exception", ex.getMessage()),
ex, showToastOnIOException);
} catch (Exception ex) {
Logger.printException(() -> "Spoof storyboard fetch failed", ex); // Should never happen.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
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;
Expand Down Expand Up @@ -48,7 +50,7 @@ private static void loadCustomSeekbarColor() {
seekbarColor = Color.parseColor(Settings.SEEKBAR_CUSTOM_COLOR_VALUE.get());
Color.colorToHSV(seekbarColor, customSeekbarColorHSV);
} catch (Exception ex) {
Utils.showToastShort("Invalid seekbar color value. Using default value.");
Utils.showToastShort(str("revanced_seekbar_custom_color_invalid"));
Settings.SEEKBAR_CUSTOM_COLOR_VALUE.resetToDefault();
loadCustomSeekbarColor();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ public static void initialize(Activity licenseActivity) {
String toolbarTitleResourceName;
String dataString = licenseActivity.getIntent().getDataString();
switch (dataString) {
case "sponsorblock_settings":
toolbarTitleResourceName = "revanced_sponsorblock_settings_title";
case "revanced_sb_settings_intent":
toolbarTitleResourceName = "revanced_sb_settings_title";
fragment = new SponsorBlockPreferenceFragment();
break;
case "ryd_settings":
case "revanced_ryd_settings_intent":
toolbarTitleResourceName = "revanced_ryd_settings_title";
fragment = new ReturnYouTubeDislikePreferenceFragment();
break;
case "revanced_settings":
case "revanced_settings_intent":
toolbarTitleResourceName = "revanced_settings_title";
fragment = new ReVancedPreferenceFragment();
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,9 @@ public void onCreate(Bundle savedInstanceState) {

toastOnRYDNotAvailable = new SwitchPreference(context);
toastOnRYDNotAvailable.setChecked(Settings.RYD_TOAST_ON_CONNECTION_ERROR.get());
toastOnRYDNotAvailable.setTitle(str("ryd_toast_on_connection_error_title"));
toastOnRYDNotAvailable.setSummaryOn(str("ryd_toast_on_connection_error_summary_on"));
toastOnRYDNotAvailable.setSummaryOff(str("ryd_toast_on_connection_error_summary_off"));
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();
Expand Down
Loading

0 comments on commit 7ae10be

Please sign in to comment.