001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import java.io.IOException;
005import java.io.InputStream;
006import java.net.URL;
007import java.util.List;
008import java.util.Optional;
009import java.util.concurrent.atomic.AtomicReference;
010import java.util.function.BiConsumer;
011import java.util.stream.Collectors;
012
013import javax.xml.parsers.ParserConfigurationException;
014import javax.xml.xpath.XPath;
015import javax.xml.xpath.XPathConstants;
016import javax.xml.xpath.XPathExpressionException;
017import javax.xml.xpath.XPathFactory;
018
019import org.openstreetmap.josm.data.Bounds;
020import org.openstreetmap.josm.data.coor.LatLon;
021import org.w3c.dom.Document;
022import org.w3c.dom.NamedNodeMap;
023import org.w3c.dom.Node;
024import org.w3c.dom.NodeList;
025import org.xml.sax.SAXException;
026
027/**
028 * Interaction with Mediawiki instances, such as the OSM wiki.
029 * @since 14641
030 */
031public class Mediawiki {
032
033    private final String baseUrl;
034
035    /**
036     * Constructs a new {@code Mediawiki} for the given base URL.
037     * @param baseUrl The wiki base URL
038     */
039    public Mediawiki(String baseUrl) {
040        this.baseUrl = baseUrl;
041    }
042
043    /**
044     * Determines which page exists on the Mediawiki instance.
045     * @param pages the pages to check
046     * @return the first existing page
047     * @throws IOException if any I/O error occurs
048     * @throws ParserConfigurationException if a parser cannot be created
049     * @throws SAXException if any XML error occurs
050     * @throws XPathExpressionException if any error in an XPath expression occurs
051     */
052    public Optional<String> findExistingPage(List<String> pages)
053            throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
054        List<String> distinctPages = pages.stream().distinct().collect(Collectors.toList());
055        // find a page that actually exists in the wiki
056        // API documentation: https://wiki.openstreetmap.org/w/api.php?action=help&modules=query
057        final URL url = new URL(baseUrl + "/w/api.php?action=query&format=xml&titles=" + distinctPages.stream()
058                .map(Utils::encodeUrl)
059                .collect(Collectors.joining(Utils.encodeUrl("|")))
060        );
061        final Document document = getDocument(url);
062        final XPath xPath = XPathFactory.newInstance().newXPath();
063        AtomicReference<String> normalized = new AtomicReference<>();
064        AtomicReference<String> page = new AtomicReference<>();
065        xPath.setXPathVariableResolver(v -> {
066            if ("page".equals(v.getLocalPart())) {
067                return page.get();
068            } else if ("normalized".equals(v.getLocalPart())) {
069                return normalized.get();
070            }
071            throw new IllegalArgumentException();
072        });
073        for (String p : distinctPages) {
074            page.set(p);
075            normalized.set(xPath.evaluate("/api/query/normalized/n[@from=$page]/@to", document));
076            if (Utils.isEmpty(normalized.get())) {
077                normalized.set(page.get());
078            }
079            final Node node = (Node) xPath.evaluate("/api/query/pages/page[@title=$normalized]", document, XPathConstants.NODE);
080            if (node != null
081                    && node.getAttributes().getNamedItem("missing") == null
082                    && node.getAttributes().getNamedItem("invalid") == null) {
083                return Optional.of(page.get());
084            }
085        }
086        return Optional.empty();
087    }
088
089    private static Document getDocument(URL url) throws IOException, ParserConfigurationException, SAXException {
090        final HttpClient.Response conn = HttpClient.create(url).connect();
091        try (InputStream content = conn.getContent()) {
092            return XmlUtils.parseSafeDOM(content);
093        } finally {
094            conn.disconnect();
095        }
096    }
097
098    /**
099     * Searches geocoded images from <a href="https://commons.wikimedia.org/">Wikimedia Commons</a> for the given bounding box.
100     * @param bounds the bounds to load
101     * @param imageConsumer a consumer to receive the file title and the coordinates for every geocoded image
102     * @throws IOException if any I/O error occurs
103     * @throws ParserConfigurationException if a parser cannot be created
104     * @throws SAXException if any XML error occurs
105     * @throws XPathExpressionException if any error in an XPath expression occurs
106     */
107    public void searchGeoImages(Bounds bounds, BiConsumer<String, LatLon> imageConsumer)
108            throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
109        final URL url = new URL(getGeoImagesUrl(baseUrl, bounds));
110        final Document document = getDocument(url);
111        final XPath xPath = XPathFactory.newInstance().newXPath();
112        NodeList nodes = (NodeList) xPath.evaluate("/api/query/geosearch/gs", document, XPathConstants.NODESET);
113        for (int i = 0; i < nodes.getLength(); i++) {
114            NamedNodeMap attributes = nodes.item(i).getAttributes();
115            String title = attributes.getNamedItem("title").getNodeValue();
116            double lat = Double.parseDouble(attributes.getNamedItem("lat").getNodeValue());
117            double lon = Double.parseDouble(attributes.getNamedItem("lon").getNodeValue());
118            imageConsumer.accept(title, new LatLon(lat, lon));
119        }
120    }
121
122    /**
123     * Returns the URL for searching geolocated images in given bounds.
124     * @param baseUrl The wiki base URL
125     * @param bounds the bounds of the search area
126     * @return the URL for searching geolocated images in given bounds
127     * @since 18046
128     */
129    public static String getGeoImagesUrl(String baseUrl, Bounds bounds) {
130        String sep = Utils.encodeUrl("|");
131        return baseUrl +
132                "?format=xml" +
133                "&action=query" +
134                "&list=geosearch" +
135                "&gsnamespace=6" +
136                "&gslimit=500" +
137                "&gsprop=type" + sep + "name" +
138                "&gsbbox=" + bounds.getMaxLat() + sep + bounds.getMinLon() + sep + bounds.getMinLat() + sep + bounds.getMaxLon();
139    }
140
141    /**
142     * Computes the URL for the given filename on the MediaWiki server
143     * @param fileBaseUrl the base URL of the file MediaWiki storage, such as {@code "https://upload.wikimedia.org/wikipedia/commons/"}
144     * @param filename    the filename
145     * @return the URL for the given filename on the MediaWiki server
146     * @see <a href="https://www.mediawiki.org/wiki/Manual:$wgHashedUploadDirectory">MediaWiki $wgHashedUploadDirectory</a>
147     */
148    public static String getImageUrl(String fileBaseUrl, String filename) {
149        final String md5 = Utils.md5Hex(filename);
150        return String.join("/", Utils.strip(fileBaseUrl, "/"), md5.substring(0, 1), md5.substring(0, 2), filename);
151    }
152}