|
| 1 | +package app.revanced.extension.music.patches.misc.requests; |
| 2 | + |
| 3 | +import android.annotation.SuppressLint; |
| 4 | + |
| 5 | +import androidx.annotation.GuardedBy; |
| 6 | +import androidx.annotation.NonNull; |
| 7 | +import androidx.annotation.Nullable; |
| 8 | + |
| 9 | +import org.json.JSONException; |
| 10 | +import org.json.JSONObject; |
| 11 | + |
| 12 | +import java.io.IOException; |
| 13 | +import java.net.HttpURLConnection; |
| 14 | +import java.net.SocketTimeoutException; |
| 15 | +import java.util.HashMap; |
| 16 | +import java.util.Map; |
| 17 | +import java.util.concurrent.ExecutionException; |
| 18 | +import java.util.concurrent.Future; |
| 19 | +import java.util.concurrent.TimeUnit; |
| 20 | +import java.util.concurrent.TimeoutException; |
| 21 | + |
| 22 | +import app.revanced.extension.shared.requests.Requester; |
| 23 | +import app.revanced.extension.shared.utils.Logger; |
| 24 | +import app.revanced.extension.shared.utils.Utils; |
| 25 | + |
| 26 | +public class PipedRequester { |
| 27 | + /** |
| 28 | + * How long to keep fetches until they are expired. |
| 29 | + */ |
| 30 | + private static final long CACHE_RETENTION_TIME_MILLISECONDS = 60 * 1000; // 1 Minute |
| 31 | + |
| 32 | + private static final long MAX_MILLISECONDS_TO_WAIT_FOR_FETCH = 20 * 1000; // 20 seconds |
| 33 | + |
| 34 | + @GuardedBy("itself") |
| 35 | + private static final Map<String, PipedRequester> cache = new HashMap<>(); |
| 36 | + |
| 37 | + @SuppressLint("ObsoleteSdkInt") |
| 38 | + public static void fetchRequestIfNeeded(@NonNull String videoId, @NonNull String playlistId, final int playlistIndex) { |
| 39 | + synchronized (cache) { |
| 40 | + final long now = System.currentTimeMillis(); |
| 41 | + |
| 42 | + cache.values().removeIf(request -> { |
| 43 | + final boolean expired = request.isExpired(now); |
| 44 | + if (expired) Logger.printDebug(() -> "Removing expired stream: " + request.videoId); |
| 45 | + return expired; |
| 46 | + }); |
| 47 | + |
| 48 | + if (!cache.containsKey(videoId)) { |
| 49 | + PipedRequester pipedRequester = new PipedRequester(videoId, playlistId, playlistIndex); |
| 50 | + cache.put(videoId, pipedRequester); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + @Nullable |
| 56 | + public static PipedRequester getRequestForVideoId(@Nullable String videoId) { |
| 57 | + synchronized (cache) { |
| 58 | + return cache.get(videoId); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * TCP timeout |
| 64 | + */ |
| 65 | + private static final int TIMEOUT_TCP_DEFAULT_MILLISECONDS = 2 * 1000; // 2 seconds |
| 66 | + |
| 67 | + /** |
| 68 | + * HTTP response timeout |
| 69 | + */ |
| 70 | + private static final int TIMEOUT_HTTP_DEFAULT_MILLISECONDS = 4 * 1000; // 4 seconds |
| 71 | + |
| 72 | + @Nullable |
| 73 | + private static JSONObject send(@NonNull String videoId, @NonNull String playlistId, final int playlistIndex) { |
| 74 | + final long startTime = System.currentTimeMillis(); |
| 75 | + Logger.printDebug(() -> "Fetching piped instances (videoId: '" + videoId + |
| 76 | + "', playlistId: '" + playlistId + "', playlistIndex: '" + playlistIndex + "'"); |
| 77 | + |
| 78 | + try { |
| 79 | + HttpURLConnection connection = PipedRoutes.getPlaylistConnectionFromRoute(playlistId); |
| 80 | + connection.setConnectTimeout(TIMEOUT_TCP_DEFAULT_MILLISECONDS); |
| 81 | + connection.setReadTimeout(TIMEOUT_HTTP_DEFAULT_MILLISECONDS); |
| 82 | + |
| 83 | + final int responseCode = connection.getResponseCode(); |
| 84 | + if (responseCode == 200) return Requester.parseJSONObject(connection); |
| 85 | + |
| 86 | + handleConnectionError("API not available: " + responseCode); |
| 87 | + } catch (SocketTimeoutException ex) { |
| 88 | + handleConnectionError("Connection timeout", ex); |
| 89 | + } catch (IOException ex) { |
| 90 | + handleConnectionError("Network error", ex); |
| 91 | + } catch (Exception ex) { |
| 92 | + Logger.printException(() -> "send failed", ex); |
| 93 | + } finally { |
| 94 | + Logger.printDebug(() -> "playlist: " + playlistId + " took: " + (System.currentTimeMillis() - startTime) + "ms"); |
| 95 | + } |
| 96 | + |
| 97 | + return null; |
| 98 | + } |
| 99 | + |
| 100 | + @Nullable |
| 101 | + private static String fetch(@NonNull String videoId, @NonNull String playlistId, final int playlistIndex) { |
| 102 | + final JSONObject playlistJson = send(videoId, playlistId, playlistIndex); |
| 103 | + if (playlistJson != null) { |
| 104 | + try { |
| 105 | + final String songId = playlistJson.getJSONArray("relatedStreams") |
| 106 | + .getJSONObject(playlistIndex) |
| 107 | + .getString("url") |
| 108 | + .replaceAll("/.+=", ""); |
| 109 | + if (songId.isEmpty()) { |
| 110 | + handleConnectionError("Url is empty!"); |
| 111 | + } else if (!songId.equals(videoId)) { |
| 112 | + return songId; |
| 113 | + } |
| 114 | + } catch (JSONException e) { |
| 115 | + Logger.printDebug(() -> "Fetch failed while processing response data for response: " + playlistJson); |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + return null; |
| 120 | + } |
| 121 | + |
| 122 | + private static void handleConnectionError(@NonNull String errorMessage) { |
| 123 | + handleConnectionError(errorMessage, null); |
| 124 | + } |
| 125 | + |
| 126 | + private static void handleConnectionError(@NonNull String errorMessage, @Nullable Exception ex) { |
| 127 | + if (ex != null) { |
| 128 | + Logger.printInfo(() -> errorMessage, ex); |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + |
| 133 | + /** |
| 134 | + * Time this instance and the fetch future was created. |
| 135 | + */ |
| 136 | + private final long timeFetched; |
| 137 | + private final String videoId; |
| 138 | + private final Future<String> future; |
| 139 | + |
| 140 | + private PipedRequester(@NonNull String videoId, @NonNull String playlistId, final int playlistIndex) { |
| 141 | + this.timeFetched = System.currentTimeMillis(); |
| 142 | + this.videoId = videoId; |
| 143 | + this.future = Utils.submitOnBackgroundThread(() -> fetch(videoId, playlistId, playlistIndex)); |
| 144 | + } |
| 145 | + |
| 146 | + public boolean isExpired(long now) { |
| 147 | + final long timeSinceCreation = now - timeFetched; |
| 148 | + if (timeSinceCreation > CACHE_RETENTION_TIME_MILLISECONDS) { |
| 149 | + return true; |
| 150 | + } |
| 151 | + |
| 152 | + // Only expired if the fetch failed (API null response). |
| 153 | + return (fetchCompleted() && getStream() == null); |
| 154 | + } |
| 155 | + |
| 156 | + /** |
| 157 | + * @return if the fetch call has completed. |
| 158 | + */ |
| 159 | + public boolean fetchCompleted() { |
| 160 | + return future.isDone(); |
| 161 | + } |
| 162 | + |
| 163 | + public String getStream() { |
| 164 | + try { |
| 165 | + return future.get(MAX_MILLISECONDS_TO_WAIT_FOR_FETCH, TimeUnit.MILLISECONDS); |
| 166 | + } catch (TimeoutException ex) { |
| 167 | + Logger.printInfo(() -> "getStream timed out", ex); |
| 168 | + } catch (InterruptedException ex) { |
| 169 | + Logger.printException(() -> "getStream interrupted", ex); |
| 170 | + Thread.currentThread().interrupt(); // Restore interrupt status flag. |
| 171 | + } catch (ExecutionException ex) { |
| 172 | + Logger.printException(() -> "getStream failure", ex); |
| 173 | + } |
| 174 | + |
| 175 | + return null; |
| 176 | + } |
| 177 | +} |
0 commit comments