001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.plugins;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.Dimension;
007import java.awt.GridBagLayout;
008import java.io.ByteArrayInputStream;
009import java.io.File;
010import java.io.FilenameFilter;
011import java.io.IOException;
012import java.io.InputStream;
013import java.io.InputStreamReader;
014import java.io.PrintWriter;
015import java.net.MalformedURLException;
016import java.net.URL;
017import java.nio.charset.StandardCharsets;
018import java.util.ArrayList;
019import java.util.Arrays;
020import java.util.Collection;
021import java.util.Collections;
022import java.util.HashSet;
023import java.util.LinkedList;
024import java.util.List;
025import java.util.Optional;
026import java.util.Set;
027
028import javax.swing.JLabel;
029import javax.swing.JOptionPane;
030import javax.swing.JPanel;
031import javax.swing.JScrollPane;
032
033import org.openstreetmap.josm.Main;
034import org.openstreetmap.josm.gui.PleaseWaitRunnable;
035import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
036import org.openstreetmap.josm.gui.progress.ProgressMonitor;
037import org.openstreetmap.josm.gui.util.GuiHelper;
038import org.openstreetmap.josm.gui.widgets.JosmTextArea;
039import org.openstreetmap.josm.io.OsmTransferException;
040import org.openstreetmap.josm.spi.preferences.Config;
041import org.openstreetmap.josm.tools.GBC;
042import org.openstreetmap.josm.tools.HttpClient;
043import org.openstreetmap.josm.tools.Logging;
044import org.openstreetmap.josm.tools.Utils;
045import org.xml.sax.SAXException;
046
047/**
048 * An asynchronous task for downloading plugin lists from the configured plugin download sites.
049 * @since 2817
050 */
051public class ReadRemotePluginInformationTask extends PleaseWaitRunnable {
052
053    private Collection<String> sites;
054    private boolean canceled;
055    private HttpClient connection;
056    private List<PluginInformation> availablePlugins;
057    private boolean displayErrMsg;
058
059    protected final void init(Collection<String> sites, boolean displayErrMsg) {
060        this.sites = Optional.ofNullable(sites).orElseGet(Collections::emptySet);
061        this.availablePlugins = new LinkedList<>();
062        this.displayErrMsg = displayErrMsg;
063    }
064
065    /**
066     * Constructs a new {@code ReadRemotePluginInformationTask}.
067     *
068     * @param sites the collection of download sites. Defaults to the empty collection if null.
069     */
070    public ReadRemotePluginInformationTask(Collection<String> sites) {
071        super(tr("Download plugin list..."), false /* don't ignore exceptions */);
072        init(sites, true);
073    }
074
075    /**
076     * Constructs a new {@code ReadRemotePluginInformationTask}.
077     *
078     * @param monitor the progress monitor. Defaults to {@link NullProgressMonitor#INSTANCE} if null
079     * @param sites the collection of download sites. Defaults to the empty collection if null.
080     * @param displayErrMsg if {@code true}, a blocking error message is displayed in case of I/O exception.
081     */
082    public ReadRemotePluginInformationTask(ProgressMonitor monitor, Collection<String> sites, boolean displayErrMsg) {
083        super(tr("Download plugin list..."), monitor == null ? NullProgressMonitor.INSTANCE : monitor, false /* don't ignore exceptions */);
084        init(sites, displayErrMsg);
085    }
086
087    @Override
088    protected void cancel() {
089        canceled = true;
090        synchronized (this) {
091            if (connection != null) {
092                connection.disconnect();
093            }
094        }
095    }
096
097    @Override
098    protected void finish() {
099        // Do nothing
100    }
101
102    /**
103     * Creates the file name for the cached plugin list and the icon cache file.
104     *
105     * @param pluginDir directory of plugin for data storage
106     * @param site the name of the site
107     * @return the file name for the cache file
108     */
109    protected File createSiteCacheFile(File pluginDir, String site) {
110        String name;
111        try {
112            site = site.replaceAll("%<(.*)>", "");
113            URL url = new URL(site);
114            StringBuilder sb = new StringBuilder();
115            sb.append("site-")
116              .append(url.getHost()).append('-');
117            if (url.getPort() != -1) {
118                sb.append(url.getPort()).append('-');
119            }
120            String path = url.getPath();
121            for (int i = 0; i < path.length(); i++) {
122                char c = path.charAt(i);
123                if (Character.isLetterOrDigit(c)) {
124                    sb.append(c);
125                } else {
126                    sb.append('_');
127                }
128            }
129            sb.append(".txt");
130            name = sb.toString();
131        } catch (MalformedURLException e) {
132            name = "site-unknown.txt";
133        }
134        return new File(pluginDir, name);
135    }
136
137    /**
138     * Downloads the list from a remote location
139     *
140     * @param site the site URL
141     * @param monitor a progress monitor
142     * @return the downloaded list
143     */
144    protected String downloadPluginList(String site, final ProgressMonitor monitor) {
145        /* replace %<x> with empty string or x=plugins (separated with comma) */
146        String pl = Utils.join(",", Config.getPref().getList("plugins"));
147        String printsite = site.replaceAll("%<(.*)>", "");
148        if (pl != null && !pl.isEmpty()) {
149            site = site.replaceAll("%<(.*)>", "$1"+pl);
150        } else {
151            site = printsite;
152        }
153
154        String content = null;
155        try {
156            monitor.beginTask("");
157            monitor.indeterminateSubTask(tr("Downloading plugin list from ''{0}''", printsite));
158
159            final URL url = new URL(site);
160            if ("https".equals(url.getProtocol()) || "http".equals(url.getProtocol())) {
161                connection = HttpClient.create(url).useCache(false);
162                final HttpClient.Response response = connection.connect();
163                content = response.fetchContent();
164                if (response.getResponseCode() != 200) {
165                    throw new IOException(tr("Unsuccessful HTTP request"));
166                }
167                return content;
168            } else {
169                // e.g. when downloading from a file:// URL, we can't use HttpClient
170                try (InputStreamReader in = new InputStreamReader(url.openConnection().getInputStream(), StandardCharsets.UTF_8)) {
171                    final StringBuilder sb = new StringBuilder();
172                    final char[] buffer = new char[8192];
173                    int numChars;
174                    while ((numChars = in.read(buffer)) >= 0) {
175                        sb.append(buffer, 0, numChars);
176                        if (canceled) {
177                            return null;
178                        }
179                    }
180                    return sb.toString();
181                }
182            }
183
184        } catch (MalformedURLException e) {
185            if (canceled) return null;
186            Logging.error(e);
187            return null;
188        } catch (IOException e) {
189            if (canceled) return null;
190            handleIOException(monitor, e, content);
191            return null;
192        } finally {
193            synchronized (this) {
194                if (connection != null) {
195                    connection.disconnect();
196                }
197                connection = null;
198            }
199            monitor.finishTask();
200        }
201    }
202
203    private void handleIOException(final ProgressMonitor monitor, IOException e, String details) {
204        final String msg = e.getMessage();
205        if (details == null || details.isEmpty()) {
206            Logging.error(e.getClass().getSimpleName()+": " + msg);
207        } else {
208            Logging.error(msg + " - Details:\n" + details);
209        }
210
211        if (displayErrMsg) {
212            displayErrorMessage(monitor, msg, details, tr("Plugin list download error"), tr("JOSM failed to download plugin list:"));
213        }
214    }
215
216    private static void displayErrorMessage(final ProgressMonitor monitor, final String msg, final String details, final String title,
217            final String firstMessage) {
218        GuiHelper.runInEDTAndWait(() -> {
219            JPanel panel = new JPanel(new GridBagLayout());
220            panel.add(new JLabel(firstMessage), GBC.eol().insets(0, 0, 0, 10));
221            StringBuilder b = new StringBuilder();
222            for (String part : msg.split("(?<=\\G.{200})")) {
223                b.append(part).append('\n');
224            }
225            panel.add(new JLabel("<html><body width=\"500\"><b>"+b.toString().trim()+"</b></body></html>"), GBC.eol().insets(0, 0, 0, 10));
226            if (details != null && !details.isEmpty()) {
227                panel.add(new JLabel(tr("Details:")), GBC.eol().insets(0, 0, 0, 10));
228                JosmTextArea area = new JosmTextArea(details);
229                area.setEditable(false);
230                area.setLineWrap(true);
231                area.setWrapStyleWord(true);
232                JScrollPane scrollPane = new JScrollPane(area);
233                scrollPane.setPreferredSize(new Dimension(500, 300));
234                panel.add(scrollPane, GBC.eol().fill());
235            }
236            JOptionPane.showMessageDialog(monitor.getWindowParent(), panel, title, JOptionPane.ERROR_MESSAGE);
237        });
238    }
239
240    /**
241     * Writes the list of plugins to a cache file
242     *
243     * @param site the site from where the list was downloaded
244     * @param list the downloaded list
245     */
246    protected void cachePluginList(String site, String list) {
247        File pluginDir = Main.pref.getPluginsDirectory();
248        if (!pluginDir.exists() && !pluginDir.mkdirs()) {
249            Logging.warn(tr("Failed to create plugin directory ''{0}''. Cannot cache plugin list from plugin site ''{1}''.",
250                    pluginDir.toString(), site));
251        }
252        File cacheFile = createSiteCacheFile(pluginDir, site);
253        getProgressMonitor().subTask(tr("Writing plugin list to local cache ''{0}''", cacheFile.toString()));
254        try (PrintWriter writer = new PrintWriter(cacheFile, StandardCharsets.UTF_8.name())) {
255            writer.write(list);
256            writer.flush();
257        } catch (IOException e) {
258            // just failed to write the cache file. No big deal, but log the exception anyway
259            Logging.error(e);
260        }
261    }
262
263    /**
264     * Filter information about deprecated plugins from the list of downloaded
265     * plugins
266     *
267     * @param plugins the plugin informations
268     * @return the plugin informations, without deprecated plugins
269     */
270    protected List<PluginInformation> filterDeprecatedPlugins(List<PluginInformation> plugins) {
271        List<PluginInformation> ret = new ArrayList<>(plugins.size());
272        Set<String> deprecatedPluginNames = new HashSet<>();
273        for (PluginHandler.DeprecatedPlugin p : PluginHandler.DEPRECATED_PLUGINS) {
274            deprecatedPluginNames.add(p.name);
275        }
276        for (PluginInformation plugin: plugins) {
277            if (deprecatedPluginNames.contains(plugin.name)) {
278                continue;
279            }
280            ret.add(plugin);
281        }
282        return ret;
283    }
284
285    /**
286     * Parses the plugin list
287     *
288     * @param site the site from where the list was downloaded
289     * @param doc the document with the plugin list
290     */
291    protected void parsePluginListDocument(String site, String doc) {
292        try {
293            getProgressMonitor().subTask(tr("Parsing plugin list from site ''{0}''", site));
294            InputStream in = new ByteArrayInputStream(doc.getBytes(StandardCharsets.UTF_8));
295            List<PluginInformation> pis = new PluginListParser().parse(in);
296            availablePlugins.addAll(filterDeprecatedPlugins(pis));
297        } catch (PluginListParseException e) {
298            Logging.error(tr("Failed to parse plugin list document from site ''{0}''. Skipping site. Exception was: {1}", site, e.toString()));
299            Logging.error(e);
300        }
301    }
302
303    @Override
304    protected void realRun() throws SAXException, IOException, OsmTransferException {
305        if (sites == null) return;
306        getProgressMonitor().setTicksCount(sites.size() * 3);
307
308        // collect old cache files and remove if no longer in use
309        List<File> siteCacheFiles = new LinkedList<>();
310        for (String location : PluginInformation.getPluginLocations()) {
311            File[] f = new File(location).listFiles(
312                    (FilenameFilter) (dir, name) -> name.matches("^([0-9]+-)?site.*\\.txt$") ||
313                                                    name.matches("^([0-9]+-)?site.*-icons\\.zip$")
314            );
315            if (f != null && f.length > 0) {
316                siteCacheFiles.addAll(Arrays.asList(f));
317            }
318        }
319
320        File pluginDir = Main.pref.getPluginsDirectory();
321        for (String site: sites) {
322            String printsite = site.replaceAll("%<(.*)>", "");
323            getProgressMonitor().subTask(tr("Processing plugin list from site ''{0}''", printsite));
324            String list = downloadPluginList(site, getProgressMonitor().createSubTaskMonitor(0, false));
325            if (canceled) return;
326            siteCacheFiles.remove(createSiteCacheFile(pluginDir, site));
327            if (list != null) {
328                getProgressMonitor().worked(1);
329                cachePluginList(site, list);
330                if (canceled) return;
331                getProgressMonitor().worked(1);
332                parsePluginListDocument(site, list);
333                if (canceled) return;
334                getProgressMonitor().worked(1);
335                if (canceled) return;
336            }
337        }
338        // remove old stuff or whole update process is broken
339        for (File file: siteCacheFiles) {
340            Utils.deleteFile(file);
341        }
342    }
343
344    /**
345     * Replies true if the task was canceled
346     * @return <code>true</code> if the task was stopped by the user
347     */
348    public boolean isCanceled() {
349        return canceled;
350    }
351
352    /**
353     * Replies the list of plugins described in the downloaded plugin lists
354     *
355     * @return  the list of plugins
356     * @since 5601
357     */
358    public List<PluginInformation> getAvailablePlugins() {
359        return availablePlugins;
360    }
361}