1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 | import static org.openstreetmap.josm.tools.I18n.trn;
|
---|
6 |
|
---|
7 | import java.io.IOException;
|
---|
8 | import java.io.InputStream;
|
---|
9 | import java.net.MalformedURLException;
|
---|
10 | import java.net.URL;
|
---|
11 | import java.util.Arrays;
|
---|
12 | import java.util.Collections;
|
---|
13 | import java.util.HashMap;
|
---|
14 | import java.util.List;
|
---|
15 | import java.util.Map;
|
---|
16 | import java.util.Optional;
|
---|
17 | import java.util.function.Supplier;
|
---|
18 | import java.util.function.UnaryOperator;
|
---|
19 | import java.util.regex.Matcher;
|
---|
20 | import java.util.regex.Pattern;
|
---|
21 | import java.util.stream.Collectors;
|
---|
22 |
|
---|
23 | import javax.json.Json;
|
---|
24 | import javax.json.JsonArray;
|
---|
25 | import javax.json.JsonReader;
|
---|
26 | import javax.json.JsonValue;
|
---|
27 |
|
---|
28 | import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
|
---|
29 | import org.openstreetmap.josm.data.osm.OsmUtils;
|
---|
30 | import org.openstreetmap.josm.data.preferences.CachingProperty;
|
---|
31 | import org.openstreetmap.josm.data.preferences.ListProperty;
|
---|
32 | import org.openstreetmap.josm.io.CachedFile;
|
---|
33 |
|
---|
34 | /**
|
---|
35 | * Extracts web links from OSM tags.
|
---|
36 | *
|
---|
37 | * The following rules are used:
|
---|
38 | * <ul>
|
---|
39 | * <li>internal rules for basic tags</li>
|
---|
40 | * <li>rules from Wikidata based on OSM tag or key (P1282); formatter URL (P1630); third-party formatter URL (P3303)</li>
|
---|
41 | * <li>rules from OSM Sophox based on permanent key ID (P16); formatter URL (P8)</li>
|
---|
42 | * </ul>
|
---|
43 | *
|
---|
44 | * @since 15673
|
---|
45 | */
|
---|
46 | public final class Tag2Link {
|
---|
47 |
|
---|
48 | // Related implementations:
|
---|
49 | // - https://github.com/openstreetmap/openstreetmap-website/blob/master/app/helpers/browse_tags_helper.rb
|
---|
50 |
|
---|
51 | /**
|
---|
52 | * Maps OSM keys to formatter URLs from Wikidata and OSM Sophox where {@code "$1"} has to be replaced by a value.
|
---|
53 | */
|
---|
54 | static final MultiMap<String, String> wikidataRules = new MultiMap<>();
|
---|
55 |
|
---|
56 | static final Map<String, UnaryOperator<String>> valueFormatter = Collections.singletonMap(
|
---|
57 | "ref:bag", v -> String.format("%16s", v).replace(' ', '0')
|
---|
58 | );
|
---|
59 |
|
---|
60 | static final String languagePattern = LanguageInfo.getLanguageCodes(null).stream()
|
---|
61 | .map(Pattern::quote)
|
---|
62 | .collect(Collectors.joining("|"));
|
---|
63 |
|
---|
64 | static final ListProperty PREF_SOURCE = new ListProperty("tag2link.source",
|
---|
65 | Collections.singletonList("resource://META-INF/resources/webjars/tag2link/2020.10.18/index.json"));
|
---|
66 |
|
---|
67 | static final CachingProperty<List<String>> PREF_SEARCH_ENGINES = new ListProperty("tag2link.search",
|
---|
68 | Arrays.asList("https://duckduckgo.com/?q=$1", "https://www.google.com/search?q=$1")).cached();
|
---|
69 |
|
---|
70 | private Tag2Link() {
|
---|
71 | // private constructor for utility class
|
---|
72 | }
|
---|
73 |
|
---|
74 | /**
|
---|
75 | * Represents an operation that accepts a link.
|
---|
76 | */
|
---|
77 | @FunctionalInterface
|
---|
78 | public interface LinkConsumer {
|
---|
79 | /**
|
---|
80 | * Performs the operation on the given arguments.
|
---|
81 | * @param name the name/label of the link
|
---|
82 | * @param url the URL of the link
|
---|
83 | * @param icon the icon to use
|
---|
84 | */
|
---|
85 | void acceptLink(String name, String url, ImageResource icon);
|
---|
86 | }
|
---|
87 |
|
---|
88 | /**
|
---|
89 | * Initializes the tag2link rules
|
---|
90 | */
|
---|
91 | public static void initialize() {
|
---|
92 | try {
|
---|
93 | wikidataRules.clear();
|
---|
94 | for (String source : PREF_SOURCE.get()) {
|
---|
95 | initializeFromResources(new CachedFile(source));
|
---|
96 | }
|
---|
97 | } catch (Exception e) {
|
---|
98 | Logging.error("Failed to initialize tag2link rules");
|
---|
99 | Logging.error(e);
|
---|
100 | }
|
---|
101 | }
|
---|
102 |
|
---|
103 | /**
|
---|
104 | * Initializes the tag2link rules from the resources.
|
---|
105 | *
|
---|
106 | * @param resource the source
|
---|
107 | * @throws IOException in case of I/O error
|
---|
108 | */
|
---|
109 | private static void initializeFromResources(CachedFile resource) throws IOException {
|
---|
110 | final JsonArray rules;
|
---|
111 | try (InputStream inputStream = resource.getInputStream();
|
---|
112 | JsonReader jsonReader = Json.createReader(inputStream)) {
|
---|
113 | rules = jsonReader.readArray();
|
---|
114 | }
|
---|
115 |
|
---|
116 | for (JsonValue rule : rules) {
|
---|
117 | final String key = rule.asJsonObject().getString("key");
|
---|
118 | final String url = rule.asJsonObject().getString("url");
|
---|
119 | if (key.startsWith("Key:")) {
|
---|
120 | wikidataRules.put(key.substring("Key:".length()), url);
|
---|
121 | }
|
---|
122 | }
|
---|
123 | // We handle those keys ourselves
|
---|
124 | wikidataRules.keySet().removeIf(key -> key.matches("^(.+[:_])?website([:_].+)?$")
|
---|
125 | || key.matches("^(.+[:_])?url([:_].+)?$")
|
---|
126 | || key.matches("wikimedia_commons|image")
|
---|
127 | || key.matches("wikipedia(:(?<lang>\\p{Lower}{2,}))?")
|
---|
128 | || key.matches("(.*:)?wikidata"));
|
---|
129 |
|
---|
130 | final int size = wikidataRules.size();
|
---|
131 | Logging.info(trn(
|
---|
132 | "Obtained {0} Tag2Link rule from {1}",
|
---|
133 | "Obtained {0} Tag2Link rules from {1}",
|
---|
134 | size, size, resource));
|
---|
135 | }
|
---|
136 |
|
---|
137 | /**
|
---|
138 | * Generates the links for the tag given by {@code key} and {@code value}, and sends 0, 1 or more links to the {@code linkConsumer}.
|
---|
139 | * @param key the tag key
|
---|
140 | * @param value the tag value
|
---|
141 | * @param linkConsumer the receiver of the generated links
|
---|
142 | */
|
---|
143 | public static void getLinksForTag(String key, String value, LinkConsumer linkConsumer) {
|
---|
144 |
|
---|
145 | if (value == null || value.isEmpty()) {
|
---|
146 | return;
|
---|
147 | }
|
---|
148 |
|
---|
149 | final HashMap<OsmPrimitiveType, Optional<ImageResource>> memoize = new HashMap<>();
|
---|
150 | final Supplier<ImageResource> imageResource = () -> memoize
|
---|
151 | .computeIfAbsent(OsmPrimitiveType.NODE, type -> OsmPrimitiveImageProvider.getResource(key, value, type))
|
---|
152 | .orElse(null);
|
---|
153 |
|
---|
154 | // Search
|
---|
155 | if (key.matches("^(.+[:_])?name([:_]" + languagePattern + ")?$")) {
|
---|
156 | final ImageResource search = new ImageProvider("dialogs/search").getResource();
|
---|
157 | PREF_SEARCH_ENGINES.get().forEach(url ->
|
---|
158 | linkConsumer.acceptLink(tr("Search on {0}", getHost(url, url)), url.replace("$1", Utils.encodeUrl(value)), search));
|
---|
159 | }
|
---|
160 |
|
---|
161 | // Common
|
---|
162 | final String validURL = value.startsWith("http:") || value.startsWith("https:")
|
---|
163 | ? value
|
---|
164 | : value.startsWith("www.")
|
---|
165 | ? "http://" + value
|
---|
166 | : null;
|
---|
167 | if (key.matches("^(.+[:_])?website([:_].+)?$") && validURL != null) {
|
---|
168 | linkConsumer.acceptLink(getLinkName(validURL, key), validURL, imageResource.get());
|
---|
169 | }
|
---|
170 | if (key.matches("^(.+[:_])?source([:_].+)?$") && validURL != null) {
|
---|
171 | linkConsumer.acceptLink(getLinkName(validURL, key), validURL, imageResource.get());
|
---|
172 | }
|
---|
173 | if (key.matches("^(.+[:_])?url([:_].+)?$") && validURL != null) {
|
---|
174 | linkConsumer.acceptLink(getLinkName(validURL, key), validURL, imageResource.get());
|
---|
175 | }
|
---|
176 | if (key.matches("image") && validURL != null) {
|
---|
177 | linkConsumer.acceptLink(tr("View image"), validURL, imageResource.get());
|
---|
178 | }
|
---|
179 |
|
---|
180 | // Wikimedia
|
---|
181 | final Matcher keyMatcher = Pattern.compile("wikipedia(:(?<lang>\\p{Lower}{2,}))?").matcher(key);
|
---|
182 | final Matcher valueMatcher = Pattern.compile("((?<lang>\\p{Lower}{2,}):)?(?<article>.*)").matcher(value);
|
---|
183 | if (keyMatcher.matches() && valueMatcher.matches()) {
|
---|
184 | final String lang = Utils.firstNotEmptyString("en", keyMatcher.group("lang"), valueMatcher.group("lang"));
|
---|
185 | final String url = "https://" + lang + ".wikipedia.org/wiki/" + valueMatcher.group("article").replace(' ', '_');
|
---|
186 | linkConsumer.acceptLink(tr("View Wikipedia article"), url, imageResource.get());
|
---|
187 | }
|
---|
188 | if (key.matches("(.*:)?wikidata")) {
|
---|
189 | OsmUtils.splitMultipleValues(value).forEach(q -> linkConsumer.acceptLink(
|
---|
190 | tr("View Wikidata item"), "https://www.wikidata.org/wiki/" + q, imageResource.get()));
|
---|
191 | }
|
---|
192 | if (key.matches("(.*:)?species")) {
|
---|
193 | final String url = "https://species.wikimedia.org/wiki/" + value;
|
---|
194 | linkConsumer.acceptLink(getLinkName(url, key), url, imageResource.get());
|
---|
195 | }
|
---|
196 | if (key.matches("wikimedia_commons|image") && value.matches("(?i:File):.*")) {
|
---|
197 | OsmUtils.splitMultipleValues(value).forEach(i -> linkConsumer.acceptLink(
|
---|
198 | tr("View image on Wikimedia Commons"), "https://commons.wikimedia.org/wiki/" + i, imageResource.get()));
|
---|
199 | }
|
---|
200 | if (key.matches("wikimedia_commons|image") && value.matches("(?i:Category):.*")) {
|
---|
201 | OsmUtils.splitMultipleValues(value).forEach(i -> linkConsumer.acceptLink(
|
---|
202 | tr("View category on Wikimedia Commons"), "https://commons.wikimedia.org/wiki/" + i, imageResource.get()));
|
---|
203 | }
|
---|
204 |
|
---|
205 | wikidataRules.getValues(key).forEach(urlFormatter -> {
|
---|
206 | final String formattedValue = valueFormatter.getOrDefault(key, x -> x).apply(value);
|
---|
207 | final String url = urlFormatter.replace("$1", formattedValue);
|
---|
208 | linkConsumer.acceptLink(getLinkName(url, key), url, imageResource.get());
|
---|
209 | });
|
---|
210 | }
|
---|
211 |
|
---|
212 | private static String getLinkName(String url, String fallback) {
|
---|
213 | return tr("Open {0}", getHost(url, fallback));
|
---|
214 | }
|
---|
215 |
|
---|
216 | private static String getHost(String url, String fallback) {
|
---|
217 | try {
|
---|
218 | return new URL(url).getHost().replaceFirst("^www\\.", "");
|
---|
219 | } catch (MalformedURLException e) {
|
---|
220 | return fallback;
|
---|
221 | }
|
---|
222 | }
|
---|
223 |
|
---|
224 | }
|
---|