diff --git a/WordPressUtils/src/androidTest/java/org/wordpress/android/util/PhotonUtilsTest.java b/WordPressUtils/src/androidTest/java/org/wordpress/android/util/PhotonUtilsTest.java index 0e2d4b301..c6f3ee743 100644 --- a/WordPressUtils/src/androidTest/java/org/wordpress/android/util/PhotonUtilsTest.java +++ b/WordPressUtils/src/androidTest/java/org/wordpress/android/util/PhotonUtilsTest.java @@ -103,4 +103,12 @@ public void getPhotonImageUrlUsesSslOnHttpsImageUrl() { assertThat(photonUrl, equalTo("https://i0.wp.com/mysite.com/test.jpg?strip=info&quality=65&resize=2,1&ssl=1")); } + + @Test + public void getPhotonImageUrlWithErroneousSchemePosition() { + String imageUrl = "mysite.com/test.jpg#http://another.com"; + String photonUrl = PhotonUtils.getPhotonImageUrl(imageUrl, 1, 1); + + assertThat(photonUrl, equalTo(imageUrl)); + } } diff --git a/WordPressUtils/src/main/java/org/wordpress/android/util/PhotonUtils.java b/WordPressUtils/src/main/java/org/wordpress/android/util/PhotonUtils.java index 2f12eb05f..e54d346f8 100644 --- a/WordPressUtils/src/main/java/org/wordpress/android/util/PhotonUtils.java +++ b/WordPressUtils/src/main/java/org/wordpress/android/util/PhotonUtils.java @@ -52,6 +52,8 @@ public static String getPhotonImageUrl(String imageUrl, int width, int height, Q return ""; } + String originalUrl = imageUrl; + // make sure it's valid int schemePos = imageUrl.indexOf("://"); if (schemePos == -1) { @@ -138,6 +140,12 @@ public static String getPhotonImageUrl(String imageUrl, int width, int height, Q query += "&ssl=1"; } - return "https://i0.wp.com/" + imageUrl.substring(schemePos + 3, imageUrl.length()) + query; + int beginIndex = schemePos + 3; + if (beginIndex < 0 || beginIndex > imageUrl.length()) { + // Fallback to original URL if the beginIndex is invalid to avoid `StringIndexOutOfBoundsException` + // Ref: https://github.com/wordpress-mobile/WordPress-Android/issues/18626 + return originalUrl; + } + return "https://i0.wp.com/" + imageUrl.substring(beginIndex) + query; } }