|
| 1 | +package com.openelements.content; |
| 2 | + |
| 3 | +import java.net.URI; |
| 4 | +import java.util.ArrayDeque; |
| 5 | +import java.util.Deque; |
| 6 | +import java.util.HashSet; |
| 7 | +import java.util.LinkedHashMap; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.Set; |
| 11 | +import org.jsoup.Jsoup; |
| 12 | +import org.jsoup.nodes.Document; |
| 13 | +import org.jsoup.nodes.Element; |
| 14 | +import org.jsoup.parser.Parser; |
| 15 | +import org.slf4j.Logger; |
| 16 | +import org.slf4j.LoggerFactory; |
| 17 | +import org.springframework.stereotype.Component; |
| 18 | +import org.springframework.web.client.RestClient; |
| 19 | + |
| 20 | +/** |
| 21 | + * Discovers the candidate URLs of a {@code website} {@link ContentSource}. |
| 22 | + * |
| 23 | + * <p>The primary strategy reads the source's configured sitemaps: each sitemap is fetched and, if it |
| 24 | + * is a {@code <sitemapindex>}, its child sitemaps are followed recursively; {@code <urlset>} entries |
| 25 | + * contribute their {@code <loc>} and optional {@code <lastmod>}. Every discovered URL is filtered |
| 26 | + * through the source's Ant-glob include/exclude rules via {@link UrlMatcher}. |
| 27 | + * |
| 28 | + * <p>When a source declares no sitemaps, discovery falls back to a bounded, same-host link-following |
| 29 | + * crawl from the {@code baseUrl}: it follows links up to {@link #MAX_FALLBACK_DEPTH} levels deep, |
| 30 | + * guarded by a visited-set (so cycles terminate) and a total-page cap. |
| 31 | + * |
| 32 | + * <p>Discovery is fault-tolerant: a sitemap that cannot be fetched or parsed is logged and skipped; |
| 33 | + * it never aborts discovery of the other sitemaps or the source as a whole. |
| 34 | + */ |
| 35 | +@Component |
| 36 | +public class SitemapCrawler { |
| 37 | + |
| 38 | + private static final Logger log = LoggerFactory.getLogger(SitemapCrawler.class); |
| 39 | + |
| 40 | + /** Maximum link-following depth for the no-sitemap fallback crawl. */ |
| 41 | + static final int MAX_FALLBACK_DEPTH = 3; |
| 42 | + |
| 43 | + /** Safety cap on the number of pages fetched during a fallback crawl. */ |
| 44 | + static final int MAX_FALLBACK_PAGES = 200; |
| 45 | + |
| 46 | + /** Guard against pathologically nested (or self-referential) sitemap indexes. */ |
| 47 | + private static final int MAX_SITEMAP_DEPTH = 10; |
| 48 | + |
| 49 | + private final RestClient restClient; |
| 50 | + private final UrlMatcher urlMatcher; |
| 51 | + |
| 52 | + public SitemapCrawler(RestClient.Builder restClientBuilder, UrlMatcher urlMatcher) { |
| 53 | + this.restClient = restClientBuilder.build(); |
| 54 | + this.urlMatcher = urlMatcher; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Discovers the in-scope URLs of a source. |
| 59 | + * |
| 60 | + * @param source the source to crawl |
| 61 | + * @return the discovered items whose URL path is included by the source (order preserved, deduplicated) |
| 62 | + */ |
| 63 | + public List<DiscoveredItem> discover(ContentSource source) { |
| 64 | + if (source.sitemaps().isEmpty()) { |
| 65 | + return fallbackCrawl(source); |
| 66 | + } |
| 67 | + |
| 68 | + Map<String, DiscoveredItem> collected = new LinkedHashMap<>(); |
| 69 | + Set<String> visitedSitemaps = new HashSet<>(); |
| 70 | + for (String sitemapPath : source.sitemaps()) { |
| 71 | + String sitemapUrl = resolve(source.baseUrl(), sitemapPath); |
| 72 | + collectSitemap(sitemapUrl, collected, visitedSitemaps, 0); |
| 73 | + } |
| 74 | + |
| 75 | + return collected.values().stream() |
| 76 | + .filter(item -> urlMatcher.matches(source, item.url())) |
| 77 | + .toList(); |
| 78 | + } |
| 79 | + |
| 80 | + private void collectSitemap(String sitemapUrl, Map<String, DiscoveredItem> collected, |
| 81 | + Set<String> visitedSitemaps, int depth) { |
| 82 | + if (depth > MAX_SITEMAP_DEPTH || !visitedSitemaps.add(sitemapUrl)) { |
| 83 | + return; |
| 84 | + } |
| 85 | + String xml; |
| 86 | + try { |
| 87 | + xml = fetch(sitemapUrl); |
| 88 | + } catch (Exception e) { |
| 89 | + log.warn("Skipping unreachable sitemap {}: {}", sitemapUrl, e.toString()); |
| 90 | + return; |
| 91 | + } |
| 92 | + try { |
| 93 | + Document doc = Jsoup.parse(xml, sitemapUrl, Parser.xmlParser()); |
| 94 | + var childSitemaps = doc.select("sitemapindex > sitemap > loc"); |
| 95 | + if (!childSitemaps.isEmpty()) { |
| 96 | + for (Element loc : childSitemaps) { |
| 97 | + String childUrl = loc.text().trim(); |
| 98 | + if (!childUrl.isEmpty()) { |
| 99 | + collectSitemap(childUrl, collected, visitedSitemaps, depth + 1); |
| 100 | + } |
| 101 | + } |
| 102 | + return; |
| 103 | + } |
| 104 | + for (Element urlEntry : doc.select("urlset > url")) { |
| 105 | + Element loc = urlEntry.selectFirst("loc"); |
| 106 | + if (loc == null || loc.text().trim().isEmpty()) { |
| 107 | + continue; |
| 108 | + } |
| 109 | + String url = loc.text().trim(); |
| 110 | + Element lastmod = urlEntry.selectFirst("lastmod"); |
| 111 | + String lastmodValue = lastmod == null || lastmod.text().trim().isEmpty() |
| 112 | + ? null : lastmod.text().trim(); |
| 113 | + collected.putIfAbsent(url, new DiscoveredItem(url, lastmodValue)); |
| 114 | + } |
| 115 | + } catch (Exception e) { |
| 116 | + log.warn("Skipping malformed sitemap {}: {}", sitemapUrl, e.toString()); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + private List<DiscoveredItem> fallbackCrawl(ContentSource source) { |
| 121 | + String host = hostOf(source.baseUrl()); |
| 122 | + Map<String, DiscoveredItem> results = new LinkedHashMap<>(); |
| 123 | + Set<String> visited = new HashSet<>(); |
| 124 | + Deque<CrawlEntry> queue = new ArrayDeque<>(); |
| 125 | + queue.add(new CrawlEntry(source.baseUrl(), 0)); |
| 126 | + |
| 127 | + while (!queue.isEmpty() && visited.size() < MAX_FALLBACK_PAGES) { |
| 128 | + CrawlEntry entry = queue.poll(); |
| 129 | + if (!visited.add(entry.url())) { |
| 130 | + continue; |
| 131 | + } |
| 132 | + String html; |
| 133 | + try { |
| 134 | + html = fetch(entry.url()); |
| 135 | + } catch (Exception e) { |
| 136 | + log.warn("Skipping unreachable page {}: {}", entry.url(), e.toString()); |
| 137 | + continue; |
| 138 | + } |
| 139 | + Document doc = Jsoup.parse(html, entry.url()); |
| 140 | + for (Element anchor : doc.select("a[href]")) { |
| 141 | + String link = stripFragment(anchor.absUrl("href")); |
| 142 | + if (link.isEmpty() || !host.equalsIgnoreCase(hostOf(link))) { |
| 143 | + continue; |
| 144 | + } |
| 145 | + if (urlMatcher.matches(source, link)) { |
| 146 | + results.putIfAbsent(link, new DiscoveredItem(link, null)); |
| 147 | + } |
| 148 | + if (entry.depth() < MAX_FALLBACK_DEPTH && !visited.contains(link)) { |
| 149 | + queue.add(new CrawlEntry(link, entry.depth() + 1)); |
| 150 | + } |
| 151 | + } |
| 152 | + } |
| 153 | + if (visited.size() >= MAX_FALLBACK_PAGES) { |
| 154 | + log.warn("Fallback crawl of {} hit the {}-page cap; discovery may be incomplete", |
| 155 | + source.baseUrl(), MAX_FALLBACK_PAGES); |
| 156 | + } |
| 157 | + return List.copyOf(results.values()); |
| 158 | + } |
| 159 | + |
| 160 | + private String fetch(String url) { |
| 161 | + return restClient.get().uri(URI.create(url)).retrieve().body(String.class); |
| 162 | + } |
| 163 | + |
| 164 | + private static String resolve(String baseUrl, String path) { |
| 165 | + return URI.create(baseUrl).resolve(path).toString(); |
| 166 | + } |
| 167 | + |
| 168 | + private static String hostOf(String url) { |
| 169 | + try { |
| 170 | + String host = URI.create(url).getHost(); |
| 171 | + return host == null ? "" : host; |
| 172 | + } catch (IllegalArgumentException e) { |
| 173 | + return ""; |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + private static String stripFragment(String url) { |
| 178 | + int hash = url.indexOf('#'); |
| 179 | + return hash >= 0 ? url.substring(0, hash) : url; |
| 180 | + } |
| 181 | + |
| 182 | + private record CrawlEntry(String url, int depth) { |
| 183 | + } |
| 184 | +} |
0 commit comments