Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 141 additions & 20 deletions src/main/java/com/rarchives/ripme/ripper/rippers/HitomiRipper.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.nodes.Document;

import com.rarchives.ripme.ripper.AbstractHTMLRipper;
Expand All @@ -22,7 +25,16 @@ public class HitomiRipper extends AbstractHTMLRipper {

private static final Logger logger = LogManager.getLogger(HitomiRipper.class);

private static final String DEFAULT_DOMAIN = "gold-usergeneratedcontent.net";
private static final Pattern GID_PATTERN = Pattern.compile("https?://hitomi\\.la/(?:cg|doujinshi|gamecg|manga|galleries|reader)/([^/?#]+?)(?:\\.html)?(?:[/?#]|$)");
private static final Pattern NUMERIC_PATTERN = Pattern.compile("(\\d+)");
private static final Pattern GG_B_PATTERN = Pattern.compile("b:\\s*'([^']+)'");
private static final Pattern GG_CASE_PATTERN = Pattern.compile("case\\s+(\\d+):");

private String galleryId = "";
private String ggB = "";
private Set<Integer> ggCases = new HashSet<>();
private String cdnDomain = DEFAULT_DOMAIN;

public HitomiRipper(URL url) throws IOException {
super(url);
Expand All @@ -40,30 +52,131 @@ public String getDomain() {

@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("https://hitomi.la/(cg|doujinshi|gamecg|manga)/(.+).html");
Matcher m = p.matcher(url.toExternalForm());
if (m.matches()) {
galleryId = m.group(1);
return m.group(1);
Matcher m = GID_PATTERN.matcher(url.toExternalForm());
if (m.find()) {
String idCandidate = m.group(1);
Matcher numMatcher = NUMERIC_PATTERN.matcher(idCandidate);
if (numMatcher.find()) {
galleryId = numMatcher.group(1);
return galleryId;
}
galleryId = idCandidate;
return galleryId;
}
throw new MalformedURLException("Expected hitomi URL format: " +
"https://hitomi.la/(cg|doujinshi|gamecg|manga)/ID.html - got " + url + " instead");
"https://hitomi.la/(cg|doujinshi|gamecg|manga|galleries|reader)/ID.html - got " + url + " instead");
}

private void fetchGgJs() {
try {
String ggJsUrl = "https://ltn." + cdnDomain + "/gg.js";
String ggJs = Http.url(ggJsUrl).ignoreContentType().response().body();
Matcher bMatcher = GG_B_PATTERN.matcher(ggJs);
if (bMatcher.find()) {
ggB = bMatcher.group(1);
}
Matcher caseMatcher = GG_CASE_PATTERN.matcher(ggJs);
Set<Integer> cases = new HashSet<>();
while (caseMatcher.find()) {
cases.add(Integer.parseInt(caseMatcher.group(1)));
}
ggCases = cases;
} catch (Exception e) {
logger.warn("Failed to fetch or parse gg.js from " + cdnDomain, e);
}
}

private int ggM(int g) {
return ggCases.contains(g) ? 1 : 0;
}

private String ggS(String hash) {
if (hash == null || hash.length() < 3) {
return "";
}
String lastThree = hash.substring(hash.length() - 3);
String reordered = "" + lastThree.charAt(2) + lastThree.charAt(0) + lastThree.charAt(1);
return Integer.toString(Integer.parseInt(reordered, 16), 10);
}

private String subdomainFromHash(String hash, String ext) {
String retval = "";
if ("webp".equals(ext)) {
retval = "w";
} else if ("avif".equals(ext)) {
retval = "a";
}

if (hash == null || hash.length() < 3) {
return retval + (1 + ggM(0));
}

String sub = hash.substring(hash.length() - 3);
String gHex = "" + sub.charAt(2) + sub.charAt(0) + sub.charAt(1);
try {
int g = Integer.parseInt(gHex, 16);
int m = ggM(g);
return retval + (1 + m);
} catch (NumberFormatException e) {
return retval + (1 + ggM(0));
}
}

public String urlFromHash(JSONObject imageObj) {
String hash = imageObj.getString("hash");
int hasWebp = imageObj.optInt("haswebp", 0);
int hasAvif = imageObj.optInt("hasavif", 0);

String ext;
if (hasWebp == 1) {
ext = "webp";
} else if (hasAvif == 1) {
ext = "avif";
} else {
String name = imageObj.optString("name", "");
ext = name.contains(".") ? name.substring(name.lastIndexOf('.') + 1) : "webp";
}

String sub = subdomainFromHash(hash, ext);
String b = ggB;
if (b != null && !b.isEmpty() && !b.endsWith("/")) {
b += "/";
}
return "https://" + sub + "." + cdnDomain + "/" + (b != null ? b : "") + ggS(hash) + "/" + hash + "." + ext;
}

@Override
public Document getFirstPage() throws IOException, URISyntaxException {
// if we go to /GALLERYID.js we get a nice json array of all images in the gallery
return Http.url(new URI(url.toExternalForm().replaceAll("hitomi", "ltn.hitomi").replaceAll(".html", ".js")).toURL()).ignoreContentType().get();
getGID(url);
fetchGgJs();
String jsonUrl = "https://ltn." + cdnDomain + "/galleries/" + galleryId + ".js";
return Http.url(new URI(jsonUrl).toURL()).ignoreContentType().get();
}


@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
String json = doc.text().replaceAll("var galleryinfo =", "");
JSONArray json_data = new JSONArray(json);
for (int i = 0; i < json_data.length(); i++) {
result.add("https://ba.hitomi.la/galleries/" + galleryId + "/" + json_data.getJSONObject(i).getString("name"));
String raw = doc.text();
int jsonStart = raw.indexOf('[');
int jsonEnd = raw.lastIndexOf(']');
JSONArray json_data;
if (jsonStart >= 0 && jsonEnd > jsonStart) {
json_data = new JSONArray(raw.substring(jsonStart, jsonEnd + 1));
} else {
String json = raw.replaceAll("var\\s+galleryinfo\\s*=", "").trim();
if (json.startsWith("{")) {
JSONObject obj = new JSONObject(json);
json_data = obj.optJSONArray("files");
} else {
json_data = new JSONArray(json);
}
}

if (json_data != null) {
for (int i = 0; i < json_data.length(); i++) {
JSONObject img = json_data.getJSONObject(i);
result.add(urlFromHash(img));
}
}

return result;
Expand All @@ -72,18 +185,26 @@ public List<String> getURLsFromPage(Document doc) {
@Override
public String getAlbumTitle(URL url) throws MalformedURLException, URISyntaxException {
try {
// Attempt to use album title and username as GID
Document doc = Http.url(url).get();
return getHost() + "_" + getGID(url) + "_" +
doc.select("title").text().replaceAll(" - Read Online - hentai artistcg \\| Hitomi.la", "");
} catch (IOException e) {
logger.info("Falling back");
getGID(url);
String jsonUrl = "https://ltn." + cdnDomain + "/galleries/" + galleryId + ".js";
String raw = Http.url(new URI(jsonUrl).toURL()).ignoreContentType().response().body();
String json = raw.replaceAll("var\\s+galleryinfo\\s*=", "").trim();
if (json.startsWith("{")) {
JSONObject obj = new JSONObject(json);
String title = obj.optString("title", "");
if (!title.isEmpty()) {
return getHost() + "_" + galleryId + "_" + title;
}
}
} catch (Exception e) {
logger.info("Falling back for album title", e);
}
return super.getAlbumTitle(url);
}

@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index));
String referer = "https://hitomi.la/reader/" + galleryId + ".html";
addURLToDownload(url, getPrefix(index), "", referer, null);
}
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,93 @@
package com.rarchives.ripme.tst.ripper.rippers;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;

import com.rarchives.ripme.ripper.rippers.HitomiRipper;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

import com.rarchives.ripme.ripper.rippers.HitomiRipper;

public class HitomiRipperTest extends RippersTest {

@Test
public void testGetGID() throws MalformedURLException, URISyntaxException, IOException {
HitomiRipper ripper = new HitomiRipper(new URI("https://hitomi.la/galleries/975973.html").toURL());
Assertions.assertEquals("975973", ripper.getGID(new URI("https://hitomi.la/galleries/975973.html").toURL()));
Assertions.assertEquals("975973", ripper.getGID(new URI("https://hitomi.la/reader/975973.html").toURL()));
Assertions.assertEquals("975973", ripper.getGID(new URI("https://hitomi.la/cg/test-title-975973.html").toURL()));
Assertions.assertEquals("975973", ripper.getGID(new URI("https://hitomi.la/doujinshi/test-975973.html").toURL()));
Assertions.assertEquals("975973", ripper.getGID(new URI("https://hitomi.la/manga/test-975973.html").toURL()));
Assertions.assertEquals("975973", ripper.getGID(new URI("https://hitomi.la/gamecg/test-975973.html").toURL()));
}

@Test
public void testGetGIDMalformed() throws IOException, URISyntaxException {
HitomiRipper ripper = new HitomiRipper(new URI("https://hitomi.la/galleries/975973.html").toURL());
Assertions.assertThrows(MalformedURLException.class, () -> {
ripper.getGID(new URI("https://hitomi.la/index-all.html").toURL());
});
Assertions.assertThrows(MalformedURLException.class, () -> {
ripper.getGID(new URI("https://hitomi.la/").toURL());
});
}

@Test
public void testGetURLsFromPageDeterministic() throws IOException, URISyntaxException {
HitomiRipper ripper = new HitomiRipper(new URI("https://hitomi.la/galleries/975973.html").toURL());
ripper.getGID(new URI("https://hitomi.la/galleries/975973.html").toURL());

String jsonPayload = "var galleryinfo = {\"id\":975973,\"title\":\"Test Gallery\",\"files\":[" +
"{\"name\":\"01.png\",\"hash\":\"2fdb01d761148ce291c4377387f1a31bd050b0c29313b94a057164c2bf266b77\",\"haswebp\":1,\"hasavif\":1}," +
"{\"name\":\"02.jpg\",\"hash\":\"a219bae8232c709a808cf7bf14ace6485832ba469cfa627f4fab6b1e4299fe4b\",\"haswebp\":1,\"hasavif\":0}" +
"]}";
Document doc = Jsoup.parse(jsonPayload);
List<String> urls = ripper.getURLsFromPage(doc);
Assertions.assertEquals(2, urls.size());
Assertions.assertTrue(urls.get(0).endsWith(".webp"));
Assertions.assertTrue(urls.get(0).contains("gold-usergeneratedcontent.net"));
Assertions.assertTrue(urls.get(1).endsWith(".webp"));
}

@Test
public void testUrlFromHashDeterministic() throws IOException, URISyntaxException {
HitomiRipper ripper = new HitomiRipper(new URI("https://hitomi.la/galleries/975973.html").toURL());

JSONObject img1 = new JSONObject();
img1.put("name", "01.png");
img1.put("hash", "2fdb01d761148ce291c4377387f1a31bd050b0c29313b94a057164c2bf266b77");
img1.put("haswebp", 1);
img1.put("hasavif", 1);

String url1 = ripper.urlFromHash(img1);
Assertions.assertTrue(url1.startsWith("https://w"));
Assertions.assertTrue(url1.contains(".gold-usergeneratedcontent.net/"));
Assertions.assertTrue(url1.endsWith("/1975/2fdb01d761148ce291c4377387f1a31bd050b0c29313b94a057164c2bf266b77.webp"));

JSONObject img2 = new JSONObject();
img2.put("name", "02.jpg");
img2.put("hash", "a219bae8232c709a808cf7bf14ace6485832ba469cfa627f4fab6b1e4299fe4b");
img2.put("haswebp", 0);
img2.put("hasavif", 1);

String url2 = ripper.urlFromHash(img2);
Assertions.assertTrue(url2.startsWith("https://a"));
Assertions.assertTrue(url2.endsWith("/3044/a219bae8232c709a808cf7bf14ace6485832ba469cfa627f4fab6b1e4299fe4b.avif"));
}

@Test
@Disabled("Broken ripper")
public void testRip() throws IOException, URISyntaxException {
@Tag("flaky")
public void testRipLive() throws IOException, URISyntaxException {
HitomiRipper ripper = new HitomiRipper(new URI("https://hitomi.la/galleries/975973.html").toURL());
testRipper(ripper);
Assertions.assertTrue(ripper.getGID(new URI("https://hitomi.la/galleries/975973.html").toURL()).equals("975973"));
Assertions.assertEquals("975973", ripper.getGID(new URI("https://hitomi.la/galleries/975973.html").toURL()));
}
}