├── .gitignore ├── LICENSE ├── README.md ├── pom.xml ├── resources └── org │ └── netpreserve │ └── warc2html │ └── forced.extensions ├── src └── org │ └── netpreserve │ └── warc2html │ ├── LinkRewriter.java │ ├── PathUtils.java │ ├── Resource.java │ └── Warc2Html.java ├── test └── org │ └── netpreserve │ └── warc2html │ ├── HtmlRewriterTest.java │ ├── LinkRewriterTest.java │ └── Warc2HtmlTest.java └── warc2html.png /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /.idea 3 | *.iml 4 | /data 5 | .attach_* 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | warc2html 2 | ========= 3 | 4 | Converts WARC files to static html while rewriting links to relative paths suitable for browsing offline or rehosting 5 | on a standard web server. 6 | 7 | Limitations: 8 | * Links in JavaScript are not rewritten 9 | * Assumes there's only one snapshot of each URL in the input 10 | * Does not handle resource records (yet) 11 | 12 | Usage 13 | ----- 14 | 15 | To convert a file named input.warc.gz to static HTML: 16 | 17 | java -jar warc2html.jar -o output/ input.warc.gz 18 | 19 | Alternatively if you'd like to convert a subset of records you can supply a list of records in CDX11 format and the 20 | path or URL where the corresponding WARC files are stored: 21 | 22 | java -jar warc2html.jar -o output/ -b http://server/warcs/ input.cdx 23 | 24 | Compiling 25 | --------- 26 | 27 | Install [OpenJDK 11](https://adoptium.net/) or later and [Apache Maven](https://maven.apache.org/) then compile with: 28 | 29 | mvn package 30 | 31 | File renaming 32 | ------------- 33 | 34 | Files are renamed to remove characters like "?" that are disallowed on some systems. File extensions are updated or added 35 | based on the Content-Type header according to [these rules](resources/org/netpreserve/warc2html/forced.extensions). 36 | 37 | URLs ending in / will be saved as index.html. Where two WARC records would produce the same filename they are 38 | disambiguated by adding a number like ~1, ~2, ~3 to the end of the filename. 39 | 40 | License 41 | ------- 42 | 43 | Copyright 2021 National Library of Australia \ 44 | License: [Apache 2.0](LICENSE) 45 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 8 | 4.0.0 9 | warc2html 10 | warc2html 11 | warc2html 12 | 0.1.0 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | ${basedir}/src 20 | ${basedir}/test 21 | 22 | 23 | ${basedir}/resources 24 | 25 | 26 | 27 | 28 | org.apache.maven.plugins 29 | maven-compiler-plugin 30 | 3.8.1 31 | 32 | 11 33 | 34 | 35 | 36 | org.apache.maven.plugins 37 | maven-shade-plugin 38 | 3.2.4 39 | 40 | 41 | 42 | shade 43 | 44 | 45 | false 46 | 47 | 48 | org.netpreserve.warc2html.Warc2Html 49 | 50 | 51 | 52 | 53 | *:* 54 | 55 | META-INF/*.MF 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | org.netpreserve 69 | jwarc 70 | 0.21.0 71 | 72 | 73 | org.netpreserve 74 | urlcanon 75 | 0.4.0 76 | 77 | 78 | net.htmlparser.jericho 79 | jericho-html 80 | 3.4 81 | 82 | 83 | junit 84 | junit 85 | 4.13.2 86 | test 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /resources/org/netpreserve/warc2html/forced.extensions: -------------------------------------------------------------------------------- 1 | application/gzip gz 2 | application/epub+zip epub 3 | application/java-archive jar 4 | application/json json 5 | application/ld+json jsonld 6 | application/msword doc 7 | application/rtf rtf 8 | application/ogg ogx 9 | application/pdf pdf 10 | application/vnd.apple.installer+xml mpkg 11 | application/vnd.ms-fontobject eot 12 | application/vnd.ms-excel xls 13 | application/vnd.ms-powerpoint ppt 14 | application/vnd.oasis.opendocument.presentation odp 15 | application/vnd.oasis.opendocument.spreadsheet ods 16 | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx 17 | application/vnd.openxmlformats-officedocument.presentationml.presentation pptx 18 | application/vnd.openxmlformats-officedocument.wordprocessingml.document docx 19 | application/x-abiword abw 20 | application/x-bzip2 bz2 21 | gapplication/xhtml+xml xhtml 22 | application/xml xml 23 | application/zip zip 24 | audio/aac aac 25 | audio/mpeg mp3 26 | audio/midi mid 27 | audio/ogg oga 28 | audio/opus opus 29 | audio/x-midi mid 30 | audio/wave wav 31 | audio/webm weba 32 | font/otf otf 33 | font/ttf ttf 34 | font/woff woff 35 | font/woff2 woff2 36 | image/bmp bmp 37 | image/gif gif 38 | image/jpeg jpg 39 | image/png png 40 | image/svg+xml svg 41 | image/tiff tif 42 | image/webp webp 43 | image/vnd.microsoft.icon ico 44 | text/calendar ics 45 | text/css css 46 | text/csv csv 47 | text/javascript js 48 | text/html html 49 | text/plain txt 50 | text/tab-separated-values tsv 51 | text/xml xml 52 | video/ogg ogv 53 | video/mpeg mpeg 54 | video/mpeg4 mp4 55 | video/webm webm 56 | video/x-msvideo avi -------------------------------------------------------------------------------- /src/org/netpreserve/warc2html/LinkRewriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 National Library of Australia 3 | * SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package org.netpreserve.warc2html; 7 | 8 | import net.htmlparser.jericho.CharacterReference; 9 | import net.htmlparser.jericho.HTMLElementName; 10 | import net.htmlparser.jericho.OutputDocument; 11 | import net.htmlparser.jericho.Source; 12 | 13 | import java.io.IOException; 14 | import java.io.InputStream; 15 | import java.io.OutputStream; 16 | import java.io.OutputStreamWriter; 17 | import java.net.URI; 18 | import java.util.Locale; 19 | import java.util.function.Function; 20 | import java.util.regex.Matcher; 21 | import java.util.regex.Pattern; 22 | 23 | public class LinkRewriter { 24 | private static final Pattern CSS_URL_PATTERN = Pattern.compile("(?<=[\\s:]url\\()\\s*([^ \"')]+|\"[^\"]+\"|'[^']+')\\s*(?=\\))"); 25 | 26 | static String rewriteCSS(String css, Function urlMapping) { 27 | return CSS_URL_PATTERN.matcher(css).replaceAll(match -> { 28 | String url = match.group(1); 29 | if (url.startsWith("\"") || url.startsWith("'")) { 30 | url = url.substring(1, url.length() - 1); 31 | } 32 | String replacement = urlMapping.apply(url); 33 | if (replacement == null || url.equals(replacement)) return match.group(); 34 | return replacement.replaceAll("([\"')])", "\\$1"); 35 | }); 36 | } 37 | 38 | public static long rewriteHTML(InputStream input, OutputStream output, Function urlMapping) throws IOException { 39 | Source source = new Source(input); 40 | OutputDocument outputDocument = new OutputDocument(source); 41 | long linksRewritten = 0; 42 | 43 | source.fullSequentialParse(); 44 | 45 | for (var el : source.getAllElements(HTMLElementName.STYLE)) { 46 | String css = el.getContent().toString(); 47 | String rewritten = rewriteCSS(css, urlMapping); 48 | if (rewritten != null && !css.equals(rewritten)) { 49 | outputDocument.replace(el.getContent(), rewritten); 50 | } 51 | } 52 | for (var tag : source.getAllStartTags()) { 53 | for (var attr : tag.getURIAttributes()) { 54 | if (!attr.hasValue()) continue; 55 | String url = attr.getValue(); 56 | String rewritten = urlMapping.apply(url); 57 | if (rewritten == null || rewritten.equals(url)) continue; 58 | 59 | String replacement = "\"" + CharacterReference.encode(rewritten, true) + "\""; 60 | outputDocument.replace(attr.getValueSegmentIncludingQuotes(), replacement); 61 | linksRewritten++; 62 | } 63 | } 64 | 65 | String encoding = source.getEncoding(); 66 | if (encoding == null) encoding = "iso-8859-1"; // seems to be what jericho defaults to for reading 67 | outputDocument.writeTo(new OutputStreamWriter(output, encoding)); 68 | 69 | return linksRewritten; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/org/netpreserve/warc2html/PathUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 National Library of Australia 3 | * SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package org.netpreserve.warc2html; 7 | 8 | import org.netpreserve.urlcanon.Canonicalizer; 9 | import org.netpreserve.urlcanon.ParsedUrl; 10 | 11 | 12 | import java.util.regex.Pattern; 13 | 14 | import static java.util.regex.Pattern.CASE_INSENSITIVE; 15 | 16 | public class PathUtils { 17 | private static final Pattern BAD_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f<>:\"/\\\\|?*]"); 18 | private static final Pattern WINDOWS_RESERVED_NAMES = Pattern.compile("^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?=$|\\.)", CASE_INSENSITIVE); 19 | 20 | public static String replaceBadFilenameChars(String filename) { 21 | filename = BAD_FILENAME_PATTERN.matcher(filename).replaceAll("_"); 22 | filename = WINDOWS_RESERVED_NAMES.matcher(filename).replaceAll("$1_"); 23 | if (filename.endsWith(".")) filename += "_"; 24 | return filename; 25 | } 26 | 27 | public static String[] splitExtension(String filename) { 28 | int slashOffset = filename.lastIndexOf('/'); 29 | int dotOffset = filename.lastIndexOf('.'); 30 | if (dotOffset >= 0 && dotOffset > slashOffset) { 31 | return new String[]{filename.substring(0, dotOffset), filename.substring(dotOffset)}; 32 | } else { 33 | return new String[]{filename, ""}; 34 | } 35 | } 36 | 37 | public static String pathFromUrl(String url, String forcedExtension) { 38 | ParsedUrl parsedUrl = ParsedUrl.parseUrl(url); 39 | Canonicalizer.WHATWG.canonicalize(parsedUrl); 40 | StringBuilder builder = new StringBuilder(); 41 | builder.append(parsedUrl.getHost()); 42 | if (!parsedUrl.getColonBeforePort().isEmpty()) { 43 | builder.append(";"); 44 | builder.append(parsedUrl.getPort()); 45 | } 46 | builder.append("/"); 47 | String[] segments = parsedUrl.getPath().split("/", -1); 48 | for (int i = 0; i < segments.length - 1; i++) { 49 | if (segments[i].isEmpty()) continue; 50 | builder.append(replaceBadFilenameChars(segments[i])); 51 | builder.append("/"); 52 | } 53 | 54 | String filename = replaceBadFilenameChars(segments[segments.length - 1]); 55 | if (filename.isEmpty()) filename = "index.html"; 56 | String[] basenameAndExtension = splitExtension(filename); 57 | String basename = basenameAndExtension[0]; 58 | String extension = basenameAndExtension[1]; 59 | if (forcedExtension != null) { 60 | extension = "." + forcedExtension; 61 | } 62 | 63 | builder.append(basename); 64 | if (!parsedUrl.getQuestionMark().isEmpty()) { 65 | builder.append(";"); 66 | builder.append(replaceBadFilenameChars(parsedUrl.getQuery())); 67 | } 68 | builder.append(extension); 69 | 70 | return builder.toString(); 71 | } 72 | 73 | public static String relativize(String path, String basePath) { 74 | StringBuilder builder = new StringBuilder(); 75 | String[] segments = path.split("/", -1); 76 | String[] baseSegments = basePath.split("/", -1); 77 | 78 | int i; 79 | 80 | // skip over all common prefix segments 81 | for (i = 0; i < segments.length && segments[i].equals(baseSegments[i]); i++) { 82 | // no action 83 | } 84 | 85 | // add ../ for every directory segment remaining in the base path 86 | for (int j = i; j < baseSegments.length - 1; j++) { 87 | builder.append("../"); 88 | } 89 | 90 | // add the portion of the original path after the common prefix 91 | for (; i < segments.length; i++) { 92 | builder.append(segments[i]); 93 | if (i < segments.length - 1) { 94 | builder.append("/"); 95 | } 96 | } 97 | return builder.toString(); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/org/netpreserve/warc2html/Resource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 National Library of Australia 3 | * SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package org.netpreserve.warc2html; 7 | 8 | import java.time.Instant; 9 | 10 | class Resource { 11 | final String url; 12 | final Instant instant; 13 | final int status; 14 | final String type; 15 | final String warc; 16 | final long offset; 17 | final long length; 18 | final String locationHeader; 19 | String path; 20 | 21 | public Resource(String url, Instant instant, int status, String type, String warc, long offset, long length, String locationHeader) { 22 | this.url = url; 23 | this.instant = instant; 24 | this.status = status; 25 | this.type = type; 26 | this.warc = warc; 27 | this.offset = offset; 28 | this.length = length; 29 | this.locationHeader = locationHeader; 30 | } 31 | 32 | public boolean isRedirect() { 33 | return status >= 300 && status <= 399 && locationHeader != null; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/org/netpreserve/warc2html/Warc2Html.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 National Library of Australia 3 | * SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package org.netpreserve.warc2html; 7 | 8 | import org.netpreserve.jwarc.WarcReader; 9 | import org.netpreserve.jwarc.WarcRecord; 10 | import org.netpreserve.jwarc.WarcResponse; 11 | import org.netpreserve.jwarc.ParsingException; 12 | import org.netpreserve.urlcanon.Canonicalizer; 13 | import org.netpreserve.urlcanon.ParsedUrl; 14 | 15 | import java.io.*; 16 | import java.lang.IllegalArgumentException; 17 | import java.net.HttpURLConnection; 18 | import java.net.URI; 19 | import java.net.URL; 20 | import java.nio.channels.FileChannel; 21 | import java.nio.file.Files; 22 | import java.nio.file.Path; 23 | import java.nio.file.Paths; 24 | import java.nio.file.FileSystemException; 25 | import java.time.Instant; 26 | import java.time.format.DateTimeFormatter; 27 | import java.util.*; 28 | 29 | import static java.nio.charset.StandardCharsets.UTF_8; 30 | import static java.time.ZoneOffset.UTC; 31 | 32 | public class Warc2Html { 33 | private static final DateTimeFormatter ARC_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.US).withZone(UTC); 34 | private static final Map DEFAULT_FORCED_EXTENSIONS = loadForcedExtensions(); 35 | private final Map resourcesByUrlKey = new HashMap<>(); 36 | private final Map resourcesByPath = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); 37 | private final Map forcedExtensions = new HashMap<>(DEFAULT_FORCED_EXTENSIONS); 38 | private String warcBaseLocation = ""; 39 | 40 | public static void main(String[] args) throws IOException { 41 | Warc2Html warc2Html = new Warc2Html(); 42 | Path outputDir = Paths.get("."); 43 | 44 | for (int i = 0; i < args.length; i++) { 45 | if (args[i].startsWith("-")) { 46 | switch (args[i]) { 47 | case "-h": 48 | case "--help": 49 | System.out.println("Usage: warc2html [-o outdir] file1.warc [file2.warc ...]"); 50 | System.out.println(" warc2html [-o outdir] -b http://example.org/warcs/ file1.cdx [file2.cdx ...]"); 51 | return; 52 | case "-b": 53 | case "--warc-base": 54 | warc2Html.setWarcBaseLocation(args[++i]); 55 | break; 56 | case "-o": 57 | case "--output-dir": 58 | outputDir = Paths.get(args[++i]); 59 | break; 60 | default: 61 | System.err.println("warc2html: unknown option: " + args[i]); 62 | System.exit(1); 63 | return; 64 | } 65 | } else { 66 | try (InputStream stream = new FileInputStream(args[i])) { 67 | warc2Html.load(args[i], stream); 68 | } 69 | } 70 | } 71 | 72 | warc2Html.resolveRedirects(); 73 | warc2Html.writeTo(outputDir); 74 | } 75 | 76 | public static String makeUrlKey(String url) { 77 | ParsedUrl parsedUrl = ParsedUrl.parseUrl(url); 78 | Canonicalizer.AGGRESSIVE.canonicalize(parsedUrl); 79 | return parsedUrl.toString(); 80 | } 81 | 82 | private static String ensureUniquePath(Map pathIndex, String path) { 83 | if (pathIndex.containsKey(path)) { 84 | String[] basenameAndExtension = PathUtils.splitExtension(path); 85 | for (long i = 1; pathIndex.containsKey(path); i++) { 86 | path = basenameAndExtension[0] + "~" + i + basenameAndExtension[1]; 87 | } 88 | } 89 | return path; 90 | } 91 | 92 | private static Map loadForcedExtensions() { 93 | try (var reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(Warc2Html.class.getResourceAsStream("forced.extensions"), "forced.extensions resource missing")))) { 94 | var map = new HashMap(); 95 | for (String line = reader.readLine(); line != null; line = reader.readLine()) { 96 | if (line.isBlank()) continue; 97 | String[] fields = line.strip().split("\\s+"); 98 | map.put(fields[0], fields[1]); 99 | } 100 | return Collections.unmodifiableMap(map); 101 | } catch (IOException e) { 102 | throw new RuntimeException("Error loading forced.extensions", e); 103 | } 104 | } 105 | 106 | private void load(String filename, InputStream stream) throws IOException { 107 | if (!stream.markSupported()) stream = new BufferedInputStream(stream); 108 | stream.mark(1); 109 | int firstByte = stream.read(); 110 | stream.reset(); 111 | if (firstByte == 'W' || firstByte == 0x1f || firstByte == 'f') { 112 | loadWarc(filename, stream); 113 | } else { 114 | loadCdx(new BufferedReader(new InputStreamReader(stream, UTF_8))); 115 | } 116 | } 117 | 118 | public void loadCdx(BufferedReader reader) throws IOException { 119 | for (String line = reader.readLine(); line != null; line = reader.readLine()) { 120 | if (line.isBlank() || line.startsWith(" ")) continue; 121 | 122 | String[] fields = line.split(" "); 123 | Instant instant = ARC_DATE_FORMAT.parse(fields[1], Instant::from); 124 | String url = fields[2]; 125 | String type = fields[3]; 126 | int status = fields[4].equals("-") ? 0 : Integer.parseInt(fields[4]); 127 | long length = Long.parseLong(fields[8]); 128 | long offset = Long.parseLong(fields[9]); 129 | String warc = fields[11]; 130 | String locationHeader = fields[6]; 131 | 132 | add(new Resource(url, instant, status, type, warc, offset, length, locationHeader)); 133 | } 134 | } 135 | 136 | private void loadWarc(String filename, InputStream stream) throws IOException { 137 | WarcReader reader = new WarcReader(stream); 138 | WarcRecord record = reader.next().orElse(null); 139 | while (record != null) { 140 | if (!(record instanceof WarcResponse)) { 141 | record = reader.next().orElse(null); 142 | continue; 143 | } 144 | WarcResponse response = (WarcResponse) record; 145 | String url = response.target(); 146 | if (!url.startsWith("http://") && !url.startsWith("https://")) { 147 | record = reader.next().orElse(null); 148 | continue; 149 | } 150 | Instant instant = response.date(); 151 | String type; 152 | try { 153 | type = response.payloadType().base().toString(); 154 | } catch (IllegalArgumentException e) { 155 | type = "application/octet-stream"; 156 | } 157 | int status = response.http().status(); 158 | long offset = reader.position(); 159 | String locationHeader = response.http().headers().first("Location").orElse(null); 160 | 161 | record = reader.next().orElse(null); 162 | long length = reader.position() - offset; 163 | 164 | add(new Resource(url, instant, status, type, filename, offset, length, locationHeader)); 165 | } 166 | } 167 | 168 | private void add(Resource resource) { 169 | if (resource.status >= 400) return; 170 | 171 | String path = PathUtils.pathFromUrl(resource.url, forcedExtensions.get(resource.type)); 172 | 173 | path = ensureUniquePath(resourcesByPath, path); 174 | 175 | resource.path = path; 176 | resourcesByPath.put(path, resource); 177 | 178 | String urlKey = makeUrlKey(resource.url); 179 | 180 | Resource existing = resourcesByUrlKey.get(urlKey); 181 | boolean keepExisting; 182 | 183 | if (existing == null) { 184 | keepExisting = false; 185 | } else if (existing.isRedirect() && !resource.isRedirect()) { 186 | keepExisting = false; 187 | } else if (resource.isRedirect() && !existing.isRedirect()) { 188 | keepExisting = true; 189 | } else if (resource.instant.isBefore(existing.instant)) { 190 | keepExisting = true; 191 | } else { 192 | keepExisting = false; 193 | } 194 | 195 | if (!keepExisting) { 196 | resourcesByUrlKey.put(urlKey, resource); 197 | } 198 | } 199 | 200 | protected WarcReader openWarc(String filename, long offset, long length) throws IOException { 201 | String pathOrUrl = warcBaseLocation + filename; 202 | if (pathOrUrl.startsWith("http://") || pathOrUrl.startsWith("https://")) { 203 | var connection = (HttpURLConnection) new URL(pathOrUrl).openConnection(); 204 | if (length > 0) { 205 | connection.addRequestProperty("Range", "bytes=" + offset + "-" + (offset + length - 1)); 206 | } else if (offset > 0) { 207 | connection.addRequestProperty("Range", "bytes=" + offset + "-"); 208 | } 209 | return new WarcReader(connection.getInputStream()); 210 | } else { 211 | FileChannel channel = FileChannel.open(Paths.get(pathOrUrl)); 212 | channel.position(offset); 213 | return new WarcReader(channel); 214 | } 215 | } 216 | 217 | public void writeTo(Path outDir) throws IOException { 218 | Files.createDirectories(outDir); 219 | try (var filelist = Files.newBufferedWriter(outDir.resolve("filelist.txt"))) { 220 | for (Resource resource : resourcesByPath.values()) { 221 | try (WarcReader reader = openWarc(resource.warc, resource.offset, resource.length)) { 222 | WarcRecord record; 223 | try { 224 | record = reader.next().orElseThrow(); 225 | } catch (ParsingException e) { 226 | System.out.println("Failed to parse record, skipping record and contining to next record."); 227 | continue; 228 | } 229 | if (!(record instanceof WarcResponse)) throw new IllegalStateException(); 230 | WarcResponse response = (WarcResponse) record; 231 | 232 | Path path = outDir.resolve(resource.path); 233 | Files.createDirectories(path.getParent()); 234 | 235 | long linksRewritten = 0; 236 | try { 237 | try (OutputStream output = Files.newOutputStream(path)) { 238 | InputStream input = response.http().body().stream(); 239 | if (resource.isRedirect()) { 240 | String destination = rewriteLink(resource.locationHeader, URI.create(resource.url), resource.path); 241 | if (destination == null) destination = resource.locationHeader; 242 | output.write(("\n").getBytes(UTF_8)); 243 | } else if (resource.type.equals("text/html")) { 244 | URI baseUri = URI.create(resource.url); 245 | linksRewritten = LinkRewriter.rewriteHTML(input, output, url -> rewriteLink(url, baseUri, resource.path)); 246 | } else { 247 | input.transferTo(output); 248 | } 249 | } 250 | 251 | System.out.println(resource.path + " " + resource.url + " " + resource.type + " " + linksRewritten); 252 | filelist.write(resource.path + " " + ARC_DATE_FORMAT.format(resource.instant) + " " + resource.url + 253 | " " + resource.type + " " + resource.status + " " + 254 | (resource.locationHeader == null ? "-" : resource.locationHeader) + "\r\n"); 255 | } catch (FileSystemException e) { 256 | System.out.println("ERROR: File name too long, will not extract:" + resource.path + " " + resource.url + " " + resource.type); 257 | } catch (IllegalArgumentException e) { 258 | System.out.println("ERROR: Illegal character in path, will not extract:" + resource.path + " " + resource.url + " " + resource.type); 259 | } 260 | } 261 | } 262 | } 263 | } 264 | 265 | 266 | private String rewriteLink(String url, URI baseUri, String basePath) { 267 | 268 | URI uri; 269 | try { 270 | uri = baseUri.resolve(url); 271 | } catch (IllegalArgumentException e) { 272 | return null; 273 | } 274 | Resource resource = resourcesByUrlKey.get(makeUrlKey(uri.toString())); 275 | if (resource == null) return null; 276 | return PathUtils.relativize(resource.path, basePath); 277 | } 278 | 279 | public void setWarcBaseLocation(String warcBaseLocation) { 280 | this.warcBaseLocation = warcBaseLocation; 281 | } 282 | 283 | public void resolveRedirects() { 284 | this.resourcesByUrlKey.replaceAll((key, resource) -> { 285 | if (resource.isRedirect()) { 286 | return resourcesByUrlKey.getOrDefault(makeUrlKey(resource.locationHeader), resource); 287 | } else { 288 | return resource; 289 | } 290 | }); 291 | } 292 | } 293 | -------------------------------------------------------------------------------- /test/org/netpreserve/warc2html/HtmlRewriterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 National Library of Australia 3 | * SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package org.netpreserve.warc2html; 7 | 8 | import org.junit.Test; 9 | 10 | import java.io.ByteArrayInputStream; 11 | import java.io.ByteArrayOutputStream; 12 | import java.io.IOException; 13 | import java.nio.charset.StandardCharsets; 14 | import java.util.function.Function; 15 | 16 | import static org.junit.Assert.*; 17 | 18 | public class HtmlRewriterTest { 19 | 20 | } -------------------------------------------------------------------------------- /test/org/netpreserve/warc2html/LinkRewriterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 National Library of Australia 3 | * SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package org.netpreserve.warc2html; 7 | 8 | import org.junit.Test; 9 | 10 | import java.io.ByteArrayInputStream; 11 | import java.io.ByteArrayOutputStream; 12 | import java.io.IOException; 13 | import java.nio.charset.StandardCharsets; 14 | import java.util.function.Function; 15 | 16 | import static org.junit.Assert.*; 17 | 18 | public class LinkRewriterTest { 19 | @Test 20 | public void testRewrite() throws IOException { 21 | assertEquals("link" + 22 | "", 23 | rewrite("link" + 24 | "", String::toUpperCase)); 25 | } 26 | @Test 27 | public void testRewriteCSS() { 28 | assertEquals("body { background: url(TEST.JPG); } ", LinkRewriter.rewriteCSS("body { background: url('test.jpg' ); } ", String::toUpperCase)); 29 | } 30 | 31 | public String rewrite(String html, Function mapping) throws IOException { 32 | ByteArrayOutputStream output = new ByteArrayOutputStream(); 33 | LinkRewriter.rewriteHTML(new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)), output, 34 | mapping); 35 | return output.toString(StandardCharsets.UTF_8); 36 | } 37 | } -------------------------------------------------------------------------------- /test/org/netpreserve/warc2html/Warc2HtmlTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 National Library of Australia 3 | * SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package org.netpreserve.warc2html; 7 | 8 | import org.junit.Test; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | public class Warc2HtmlTest { 13 | @Test 14 | public void sanitizeFilename() { 15 | assertEquals("hello.html_foo=1&bar=__baz", PathUtils.replaceBadFilenameChars("hello.html?foo=1&bar=<>baz")); 16 | assertEquals("nUl_.txt", PathUtils.replaceBadFilenameChars("nUl.txt")); 17 | assertEquals("._", PathUtils.replaceBadFilenameChars(".")); 18 | assertEquals("foo._", PathUtils.replaceBadFilenameChars("foo.")); 19 | } 20 | 21 | @Test 22 | public void makePath() { 23 | assertEquals("example.org/foo/bar;x=1&y=2.html", PathUtils.pathFromUrl("http://example.org/foo/bar.html?x=1&y=2", null)); 24 | assertEquals("example.org/foo/bar;x=1&y=2.txt", PathUtils.pathFromUrl("http://example.org/foo/bar.html?x=1&y=2", "txt")); 25 | } 26 | 27 | @Test 28 | public void relativizePath() { 29 | assertEquals("a", PathUtils.relativize("a", "b")); 30 | assertEquals("../a", PathUtils.relativize("a", "b/")); 31 | assertEquals("../a", PathUtils.relativize("a", "b/x")); 32 | assertEquals("c/d.html", PathUtils.relativize("a/b/c/d.html", "a/b/e.html")); 33 | assertEquals("../e.html", PathUtils.relativize("a/b/e.html", "a/b/c/d.html")); 34 | assertEquals("../../z/e.html", PathUtils.relativize("a/b/z/e.html", "a/b/c/d/e.html")); 35 | } 36 | } -------------------------------------------------------------------------------- /warc2html.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iipc/warc2html/17aafe456294f47291860fa035aca46872c3dcec/warc2html.png --------------------------------------------------------------------------------