Skip to content

Commit

Permalink
Rewrite relative URLs in MD files more intelligently
Browse files Browse the repository at this point in the history
Link URLs are now rewritten to be github.com absolute URLs instead of
raw.github.com, so that the file they point to can be opened directly
in OctoDroid.
  • Loading branch information
Fs00 committed Nov 12, 2021
1 parent 408fd23 commit fabcdc9
Showing 1 changed file with 13 additions and 15 deletions.
28 changes: 13 additions & 15 deletions app/src/main/java/com/gh4a/utils/HtmlUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -137,33 +137,31 @@ public void drawBackground(Canvas c, Paint p, int left, int right, int top, int

/**
* Rewrite relative URLs in HTML fetched e.g. from markdown files.
*
* @param html
* @param repoUser
* @param repoName
* @param branch
* @return
*/
public static String rewriteRelativeUrls(final String html, final String repoUser,
final String repoName, final String branch) {
final String baseUrl = "https://raw.github.com/" + repoUser + "/" + repoName + "/" + branch;
final StringBuffer sb = new StringBuffer();
final Pattern p = Pattern.compile("(href|src)=\"(\\S+)\"");
final Matcher m = p.matcher(html);
final String baseUrl = "https://github.com/" + repoUser + "/" + repoName + "/blob/" + branch;
String rewrittenHtml = rewriteUrlsInAttribute("href", html, baseUrl);

while (m.find()) {
String url = m.group(2);
final String baseUrlForImages = "https://raw.github.com/" + repoUser + "/" + repoName + "/" + branch;
return rewriteUrlsInAttribute("src", rewrittenHtml, baseUrlForImages);
}

private static String rewriteUrlsInAttribute(String attribute, String html, String baseUrl) {
final Matcher matcher = Pattern.compile("(" + attribute + ")=\"(\\S+)\"").matcher(html);
final StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String url = matcher.group(2);
if (!url.contains("://") && !url.startsWith("#")) {
if (url.startsWith("/")) {
url = baseUrl + url;
} else {
url = baseUrl + "/" + url;
}
}
m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "=\"" + url + "\""));
matcher.appendReplacement(sb, Matcher.quoteReplacement(matcher.group(1) + "=\"" + url + "\""));
}
m.appendTail(sb);

matcher.appendTail(sb);
return sb.toString();
}

Expand Down

0 comments on commit fabcdc9

Please sign in to comment.