|
22 | 22 |
|
23 | 23 | import java.io.IOException; |
24 | 24 | import java.nio.charset.StandardCharsets; |
| 25 | +import java.util.HashMap; |
25 | 26 |
|
26 | 27 |
|
27 | 28 | public class MarkdownActivity extends CompatActivity { |
28 | 29 | private static final String TAG = "MarkdownActivity"; |
| 30 | + private static final HashMap<String, String> redirects = new HashMap<>(4); |
| 31 | + private static final String[] variants = new String[]{ |
| 32 | + "readme.md", "README.MD", ".github/README.md" |
| 33 | + }; |
| 34 | + |
| 35 | + private static byte[] getRawMarkdown(String url) throws IOException { |
| 36 | + String newUrl = redirects.get(url); |
| 37 | + if (newUrl != null && !newUrl.equals(url)) { |
| 38 | + return Http.doHttpGet(newUrl, true); |
| 39 | + } |
| 40 | + try { |
| 41 | + return Http.doHttpGet(url, true); |
| 42 | + } catch (IOException e) { |
| 43 | + // Workaround GitHub README.md case sensitivity issue |
| 44 | + if (url.startsWith("https://raw.githubusercontent.com/") && |
| 45 | + url.endsWith("/README.md")) { |
| 46 | + String prefix = url.substring(0, url.length() - 9); |
| 47 | + for (String suffix : variants) { |
| 48 | + newUrl = prefix + suffix; |
| 49 | + try { // Try with lowercase version |
| 50 | + byte[] rawMarkdown = Http.doHttpGet(prefix + suffix, true); |
| 51 | + redirects.put(url, newUrl); // Avoid retries |
| 52 | + return rawMarkdown; |
| 53 | + } catch (IOException ignored) {} |
| 54 | + } |
| 55 | + } |
| 56 | + throw e; |
| 57 | + } |
| 58 | + } |
29 | 59 |
|
30 | 60 | @Override |
31 | 61 | protected void onCreate(@Nullable Bundle savedInstanceState) { |
@@ -73,21 +103,8 @@ protected void onCreate(@Nullable Bundle savedInstanceState) { |
73 | 103 | new Thread(() -> { |
74 | 104 | try { |
75 | 105 | Log.d(TAG, "Downloading"); |
76 | | - byte[] rawMarkdown; |
77 | | - try { |
78 | | - rawMarkdown = Http.doHttpGet(url, true); |
79 | | - } catch (IOException e) { |
80 | | - // Workaround GitHub README.md case sensitivity issue |
81 | | - if (url.startsWith("https://raw.githubusercontent.com/") && |
82 | | - url.endsWith("/README.md")) { |
83 | | - String prefix = url.substring(0, url.length() - 9); |
84 | | - try { // Try with lowercase version |
85 | | - rawMarkdown = Http.doHttpGet(prefix + "readme.md", true); |
86 | | - } catch (IOException ignored) { // Try with .github version |
87 | | - rawMarkdown = Http.doHttpGet(prefix + ".github/README.md", true); |
88 | | - } |
89 | | - } else throw e; |
90 | | - } |
| 106 | + byte[] rawMarkdown = getRawMarkdown(url); |
| 107 | + Log.d(TAG, "Encoding"); |
91 | 108 | String markdown = new String(rawMarkdown, StandardCharsets.UTF_8); |
92 | 109 | Log.d(TAG, "Done!"); |
93 | 110 | runOnUiThread(() -> { |
|
0 commit comments