Piped-Backend/src/main/java/me/kavin/piped/utils/URLUtils.java

64 lines
1.7 KiB
Java
Raw Normal View History

2020-11-12 21:19:45 +00:00
package me.kavin.piped.utils;
import me.kavin.piped.consts.Constants;
import org.apache.commons.lang3.StringUtils;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
2020-11-12 21:19:45 +00:00
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
2020-11-12 21:19:45 +00:00
public class URLUtils {
public static String silentEncode(String s) {
2021-02-24 09:52:29 +00:00
try {
return URLEncoder.encode(s, StandardCharsets.UTF_8);
2021-02-24 09:52:29 +00:00
} catch (Exception e) {
// ignored
}
return s;
2020-11-12 21:19:45 +00:00
}
public static String silentDecode(String s) {
try {
return URLDecoder.decode(s, StandardCharsets.UTF_8);
} catch (Exception e) {
// ignored
}
return s;
}
public static String substringYouTube(String s) {
return StringUtils.isEmpty(s) ? null : StringUtils.substringAfter(s, "youtube.com");
}
public static String rewriteURL(final String old) {
if (StringUtils.isEmpty(old)) return null;
URL url = null;
try {
url = new URL(old);
} catch (MalformedURLException e) {
ExceptionHandler.handle(e);
}
assert url != null;
final String host = url.getHost();
String query = url.getQuery();
boolean hasQuery = query != null;
String path = url.getPath();
if (path.contains("=")) {
path = StringUtils.substringBefore(path, "=") + "=" + StringUtils.substringAfter(path, "=").replace("-rj", "-rw");
}
return Constants.PROXY_PART + path + (hasQuery ? "?" + query + "&host=" : "?host=") + silentEncode(host);
}
2020-11-12 21:19:45 +00:00
}