001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.tr;
006
007import java.awt.event.ActionEvent;
008import java.awt.event.KeyEvent;
009import java.util.HashMap;
010import java.util.LinkedList;
011import java.util.List;
012import java.util.Map;
013import java.util.Optional;
014import java.util.concurrent.CompletableFuture;
015import java.util.concurrent.ExecutionException;
016import java.util.concurrent.Future;
017import java.util.function.Consumer;
018
019import javax.swing.JOptionPane;
020
021import org.openstreetmap.josm.actions.upload.ApiPreconditionCheckerHook;
022import org.openstreetmap.josm.actions.upload.DiscardTagsHook;
023import org.openstreetmap.josm.actions.upload.FixDataHook;
024import org.openstreetmap.josm.actions.upload.RelationUploadOrderHook;
025import org.openstreetmap.josm.actions.upload.UploadHook;
026import org.openstreetmap.josm.actions.upload.ValidateUploadHook;
027import org.openstreetmap.josm.data.APIDataSet;
028import org.openstreetmap.josm.data.conflict.ConflictCollection;
029import org.openstreetmap.josm.data.osm.Changeset;
030import org.openstreetmap.josm.gui.HelpAwareOptionPane;
031import org.openstreetmap.josm.gui.MainApplication;
032import org.openstreetmap.josm.gui.Notification;
033import org.openstreetmap.josm.gui.io.AsynchronousUploadPrimitivesTask;
034import org.openstreetmap.josm.gui.io.UploadDialog;
035import org.openstreetmap.josm.gui.io.UploadPrimitivesTask;
036import org.openstreetmap.josm.gui.layer.AbstractModifiableLayer;
037import org.openstreetmap.josm.gui.layer.OsmDataLayer;
038import org.openstreetmap.josm.gui.util.GuiHelper;
039import org.openstreetmap.josm.io.ChangesetUpdater;
040import org.openstreetmap.josm.io.UploadStrategySpecification;
041import org.openstreetmap.josm.spi.preferences.Config;
042import org.openstreetmap.josm.tools.ImageProvider;
043import org.openstreetmap.josm.tools.JosmRuntimeException;
044import org.openstreetmap.josm.tools.Logging;
045import org.openstreetmap.josm.tools.Shortcut;
046import org.openstreetmap.josm.tools.Utils;
047
048/**
049 * Action that opens a connection to the osm server and uploads all changes.
050 * <p>
051 * A dialog is displayed asking the user to specify a rectangle to grab.
052 * The url and account settings from the preferences are used.
053 * <p>
054 * If the upload fails, this action offers various options to resolve conflicts.
055 *
056 * @author imi
057 */
058public class UploadAction extends AbstractUploadAction {
059    /**
060     * The list of upload hooks. These hooks will be called one after the other
061     * when the user wants to upload data. Plugins can insert their own hooks here
062     * if they want to be able to veto an upload.
063     * <p>
064     * By default, the standard upload dialog is the only element in the list.
065     * Plugins should normally insert their code before that, so that the upload
066     * dialog is the last thing shown before upload really starts; on occasion
067     * however, a plugin might also want to insert something after that.
068     */
069    private static final List<UploadHook> UPLOAD_HOOKS = new LinkedList<>();
070    private static final List<UploadHook> LATE_UPLOAD_HOOKS = new LinkedList<>();
071
072    private static final String IS_ASYNC_UPLOAD_ENABLED = "asynchronous.upload";
073
074    static {
075        /*
076         * Calls validator before upload.
077         */
078        UPLOAD_HOOKS.add(new ValidateUploadHook());
079
080        /*
081         * Fixes database errors
082         */
083        UPLOAD_HOOKS.add(new FixDataHook());
084
085        /*
086         * Checks server capabilities before upload.
087         */
088        UPLOAD_HOOKS.add(new ApiPreconditionCheckerHook());
089
090        /*
091         * Adjusts the upload order of new relations
092         */
093        UPLOAD_HOOKS.add(new RelationUploadOrderHook());
094
095        /*
096         * Removes discardable tags like created_by on modified objects
097         */
098        LATE_UPLOAD_HOOKS.add(new DiscardTagsHook());
099    }
100
101    /**
102     * Registers an upload hook. Adds the hook at the first position of the upload hooks.
103     *
104     * @param hook the upload hook. Ignored if null.
105     */
106    public static void registerUploadHook(UploadHook hook) {
107        registerUploadHook(hook, false);
108    }
109
110    /**
111     * Registers an upload hook. Adds the hook at the first position of the upload hooks.
112     *
113     * @param hook the upload hook. Ignored if null.
114     * @param late true, if the hook should be executed after the upload dialog
115     * has been confirmed. Late upload hooks should in general succeed and not
116     * abort the upload.
117     */
118    public static void registerUploadHook(UploadHook hook, boolean late) {
119        if (hook == null) return;
120        if (late) {
121            if (!LATE_UPLOAD_HOOKS.contains(hook)) {
122                LATE_UPLOAD_HOOKS.add(0, hook);
123            }
124        } else {
125            if (!UPLOAD_HOOKS.contains(hook)) {
126                UPLOAD_HOOKS.add(0, hook);
127            }
128        }
129    }
130
131    /**
132     * Unregisters an upload hook. Removes the hook from the list of upload hooks.
133     *
134     * @param hook the upload hook. Ignored if null.
135     */
136    public static void unregisterUploadHook(UploadHook hook) {
137        if (hook == null) return;
138        UPLOAD_HOOKS.remove(hook);
139        LATE_UPLOAD_HOOKS.remove(hook);
140    }
141
142    /**
143     * Constructs a new {@code UploadAction}.
144     */
145    public UploadAction() {
146        super(tr("Upload data..."), "upload", tr("Upload all changes in the active data layer to the OSM server"),
147                Shortcut.registerShortcut("file:upload", tr("File: {0}", tr("Upload data")), KeyEvent.VK_UP, Shortcut.CTRL_SHIFT), true);
148        setHelpId(ht("/Action/Upload"));
149    }
150
151    @Override
152    protected boolean listenToSelectionChange() {
153        return false;
154    }
155
156    @Override
157    protected void updateEnabledState() {
158        OsmDataLayer editLayer = getLayerManager().getEditLayer();
159        setEnabled(editLayer != null && editLayer.requiresUploadToServer());
160    }
161
162    /**
163     * Check whether the preconditions are met to upload data from a given layer, if applicable.
164     * @param layer layer to check
165     * @return {@code true} if the preconditions are met, or not applicable
166     * @see #checkPreUploadConditions(AbstractModifiableLayer, APIDataSet)
167     */
168    public static boolean checkPreUploadConditions(AbstractModifiableLayer layer) {
169        return checkPreUploadConditions(layer,
170                layer instanceof OsmDataLayer ? new APIDataSet(((OsmDataLayer) layer).getDataSet()) : null);
171    }
172
173    protected static void alertUnresolvedConflicts(OsmDataLayer layer) {
174        HelpAwareOptionPane.showOptionDialog(
175                MainApplication.getMainFrame(),
176                tr("<html>The data to be uploaded participates in unresolved conflicts of layer ''{0}''.<br>"
177                        + "You have to resolve them first.</html>", Utils.escapeReservedCharactersHTML(layer.getName())
178                ),
179                tr("Warning"),
180                JOptionPane.WARNING_MESSAGE,
181                ht("/Action/Upload#PrimitivesParticipateInConflicts")
182        );
183    }
184
185    /**
186     * Warn user about discouraged upload, propose to cancel operation.
187     * @param layer incriminated layer
188     * @return true if the user wants to cancel, false if they want to continue
189     */
190    public static boolean warnUploadDiscouraged(AbstractModifiableLayer layer) {
191        return GuiHelper.warnUser(tr("Upload discouraged"),
192                "<html>" +
193                tr("You are about to upload data from the layer ''{0}''.<br /><br />"+
194                    "Sending data from this layer is <b>strongly discouraged</b>. If you continue,<br />"+
195                    "it may require you subsequently have to revert your changes, or force other contributors to.<br /><br />"+
196                    "Are you sure you want to continue?", Utils.escapeReservedCharactersHTML(layer.getName()))+
197                "</html>",
198                ImageProvider.get("upload"), tr("Ignore this hint and upload anyway"));
199    }
200
201    /**
202     * Check whether the preconditions are met to upload data in {@code apiData}.
203     * Makes sure upload is allowed, primitives in {@code apiData} don't participate in conflicts and
204     * runs the installed {@link UploadHook}s.
205     *
206     * @param layer the source layer of the data to be uploaded
207     * @param apiData the data to be uploaded
208     * @return true, if the preconditions are met; false, otherwise
209     */
210    public static boolean checkPreUploadConditions(AbstractModifiableLayer layer, APIDataSet apiData) {
211        try {
212            return checkPreUploadConditionsAsync(layer, apiData, null).get();
213        } catch (InterruptedException e) {
214            Thread.currentThread().interrupt();
215            throw new JosmRuntimeException(e);
216        } catch (ExecutionException e) {
217            throw new JosmRuntimeException(e);
218        }
219    }
220
221    /**
222     * Check whether the preconditions are met to upload data in {@code apiData}.
223     * Makes sure upload is allowed, primitives in {@code apiData} don't participate in conflicts and
224     * runs the installed {@link UploadHook}s.
225     *
226     * @param layer the source layer of the data to be uploaded
227     * @param apiData the data to be uploaded
228     * @param onFinish {@code true} if the preconditions are met; {@code false}, otherwise
229     * @return A future that completes when the checks are finished
230     * @since 18752
231     */
232    private static Future<Boolean> checkPreUploadConditionsAsync(AbstractModifiableLayer layer, APIDataSet apiData, Consumer<Boolean> onFinish) {
233        final CompletableFuture<Boolean> future = new CompletableFuture<>();
234        if (onFinish != null) {
235            future.thenAccept(onFinish);
236        }
237        if (layer.isUploadDiscouraged() && warnUploadDiscouraged(layer)) {
238            future.complete(false);
239        } else if (layer instanceof OsmDataLayer) {
240            OsmDataLayer osmLayer = (OsmDataLayer) layer;
241            ConflictCollection conflicts = osmLayer.getConflicts();
242            if (apiData.participatesInConflict(conflicts)) {
243                alertUnresolvedConflicts(osmLayer);
244                future.complete(false);
245            }
246        }
247        // Call all upload hooks in sequence.
248        if (!future.isDone()) {
249            MainApplication.worker.execute(() -> {
250                boolean hooks = true;
251                if (apiData != null) {
252                    hooks = UPLOAD_HOOKS.stream().allMatch(hook -> hook.checkUpload(apiData));
253                }
254                future.complete(hooks);
255            });
256        }
257        return future;
258    }
259
260    /**
261     * Uploads data to the OSM API.
262     *
263     * @param layer the source layer for the data to upload
264     * @param apiData the primitives to be added, updated, or deleted
265     */
266    public void uploadData(final OsmDataLayer layer, APIDataSet apiData) {
267        if (apiData.isEmpty()) {
268            new Notification(tr("No changes to upload.")).setIcon(JOptionPane.INFORMATION_MESSAGE).show();
269            return;
270        }
271        checkPreUploadConditionsAsync(layer, apiData, passed -> GuiHelper.runInEDT(() -> {
272            if (Boolean.TRUE.equals(passed)) {
273                realUploadData(layer, apiData);
274            } else {
275                new Notification(tr("One of the upload verification processes failed"))
276                        .setIcon(JOptionPane.WARNING_MESSAGE)
277                        .show();
278            }
279        }));
280    }
281
282    /**
283     * Uploads data to the OSM API.
284     *
285     * @param layer the source layer for the data to upload
286     * @param apiData the primitives to be added, updated, or deleted
287     */
288    private static void realUploadData(final OsmDataLayer layer, final APIDataSet apiData) {
289
290        ChangesetUpdater.check();
291
292        final UploadDialog dialog = UploadDialog.getUploadDialog();
293        dialog.setUploadedPrimitives(apiData);
294        dialog.initLifeCycle(layer.getDataSet());
295        Map<String, String> changesetTags = dialog.getChangeset().getKeys();
296        Map<String, String> originalChangesetTags = new HashMap<>(changesetTags);
297        for (UploadHook hook : UPLOAD_HOOKS) {
298            hook.modifyChangesetTags(changesetTags);
299        }
300        dialog.getModel().putAll(changesetTags);
301        if (!originalChangesetTags.equals(changesetTags)) {
302            dialog.setChangesetTagsModifiedProgramatically();
303        }
304        dialog.setVisible(true);
305        dialog.rememberUserInput();
306        if (dialog.isCanceled()) {
307            dialog.clean();
308            return;
309        }
310
311        for (UploadHook hook : LATE_UPLOAD_HOOKS) {
312            if (!hook.checkUpload(apiData)) {
313                dialog.clean();
314                return;
315            }
316        }
317
318        // Any hooks want to change the changeset tags?
319        Changeset cs = dialog.getChangeset();
320        changesetTags = cs.getKeys();
321        for (UploadHook hook : LATE_UPLOAD_HOOKS) {
322            hook.modifyChangesetTags(changesetTags);
323        }
324
325        UploadStrategySpecification uploadStrategySpecification = dialog.getUploadStrategySpecification();
326        Logging.info("Starting upload with tags {0}", changesetTags);
327        Logging.info(uploadStrategySpecification.toString());
328        Logging.info(cs.toString());
329        dialog.clean();
330
331        if (Config.getPref().getBoolean(IS_ASYNC_UPLOAD_ENABLED, true)) {
332            Optional<AsynchronousUploadPrimitivesTask> asyncUploadTask = AsynchronousUploadPrimitivesTask.createAsynchronousUploadTask(
333                    uploadStrategySpecification, layer, apiData, cs);
334
335            asyncUploadTask.ifPresent(MainApplication.worker::execute);
336        } else {
337            MainApplication.worker.execute(new UploadPrimitivesTask(uploadStrategySpecification, layer, apiData, cs));
338        }
339    }
340
341    @Override
342    public void actionPerformed(ActionEvent e) {
343        if (!isEnabled())
344            return;
345        if (MainApplication.getMap() == null) {
346            new Notification(tr("Nothing to upload. Get some data first.")).setIcon(JOptionPane.INFORMATION_MESSAGE).show();
347            return;
348        }
349        APIDataSet apiData = new APIDataSet(getLayerManager().getEditDataSet());
350        uploadData(getLayerManager().getEditLayer(), apiData);
351    }
352}