001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.io;
003
004import java.util.Arrays;
005import java.util.LinkedHashSet;
006import java.util.List;
007import java.util.Map;
008import java.util.Set;
009import java.util.stream.Collectors;
010
011import org.openstreetmap.josm.data.Version;
012import org.openstreetmap.josm.data.osm.DataSet;
013import org.openstreetmap.josm.gui.tagging.TagEditorModel;
014import org.openstreetmap.josm.gui.tagging.TagModel;
015import org.openstreetmap.josm.spi.preferences.Config;
016import org.openstreetmap.josm.tools.Utils;
017
018/**
019 * A model for the upload dialog
020 *
021 * @since 18173
022 */
023public class UploadDialogModel extends TagEditorModel {
024    /** the "created_by" changeset OSM key */
025    private static final String CREATED_BY = "created_by";
026    /** the "comment" changeset OSM key */
027    public static final String COMMENT = "comment";
028    /** the "source" changeset OSM key */
029    public static final String SOURCE = "source";
030    /** the user-agent */
031    private final String agent = Version.getInstance().getAgentString(false);
032    /** whether to extract hashtags from comment */
033    private final boolean hashtags = Config.getPref().getBoolean("upload.changeset.hashtags", true);
034
035    /** a lock to prevent loops  */
036    private boolean locked;
037
038    @Override
039    public void fireTableDataChanged() {
040        if (!locked) {
041            try {
042                locked = true;
043                // add "hashtags" if any
044                if (hashtags) {
045                    put("hashtags", findHashTags(getValue(COMMENT)));
046                }
047                // add/update "created_by"
048                final String createdBy = getValue(CREATED_BY);
049                if (createdBy.isEmpty()) {
050                    put(CREATED_BY, agent);
051                } else if (!createdBy.contains(agent)) {
052                    put(CREATED_BY, createdBy + ';' + agent);
053                }
054                super.fireTableDataChanged();
055            } finally {
056                locked = false;
057            }
058        }
059    }
060
061    /**
062     * Get the value of a key.
063     *
064     * @param key The key to retrieve
065     * @return The value (may be null)
066     */
067    public String getValue(String key) {
068        TagModel tag = get(key);
069        return tag == null ? "" : tag.getValue();
070    }
071
072    /**
073     * Extracts the list of hashtags from the comment text.
074     * @param comment The comment with the hashtags
075     * @return the hashtags separated by ";" or null
076     */
077    String findHashTags(String comment) {
078        String foundHashtags = Arrays.stream(comment.split("\\s", -1))
079            .map(s -> Utils.strip(s, ",;"))
080            .filter(s -> s.matches("#[a-zA-Z0-9][-_a-zA-Z0-9]+"))
081            .distinct().collect(Collectors.joining(";"));
082        return foundHashtags.isEmpty() ? null : foundHashtags;
083    }
084
085    /**
086     * Returns the given comment with appended hashtags from dataset changeset tags, if not already present.
087     * @param comment changeset comment. Can be null
088     * @param dataSet optional dataset, which can contain hashtags in its changeset tags
089     * @return comment with dataset changesets tags, if any, not duplicated
090     */
091    static String addHashTagsFromDataSet(String comment, DataSet dataSet) {
092        StringBuilder result = comment == null ? new StringBuilder() : new StringBuilder(comment);
093        if (dataSet != null) {
094            String hashtags = dataSet.getChangeSetTags().get("hashtags");
095            if (hashtags != null) {
096                Set<String> sanitizedHashtags = new LinkedHashSet<>();
097                for (String hashtag : hashtags.split(";", -1)) {
098                    if (comment == null || !comment.contains(hashtag)) {
099                        sanitizedHashtags.add(hashtag.startsWith("#") ? hashtag : "#" + hashtag);
100                    }
101                }
102                if (!sanitizedHashtags.isEmpty()) {
103                    result.append(' ').append(String.join(" ", sanitizedHashtags));
104                }
105            }
106        }
107        return result.toString();
108    }
109
110    /**
111     * Inserts/updates/deletes a tag.
112     * <p>
113     * Existing keys are updated. Others are added. A value of {@code null}
114     * deletes the key.
115     *
116     * @param key The key of the tag to insert.
117     * @param value The value of the tag to insert.
118     */
119    private void doPut(String key, String value) {
120        List<TagModel> l = tags.stream().filter(tm -> tm.getName().equals(key)).collect(Collectors.toList());
121        if (!l.isEmpty()) {
122            if (value != null)
123                for (TagModel tm : l) {
124                    tm.setValue(value);
125                }
126            else
127                tags.removeIf(tm -> tm.getName().equals(key));
128        } else if (value != null) {
129            tags.add(new TagModel(key, value));
130        }
131    }
132
133    /**
134     * Inserts/updates/deletes a tag.
135     * <p>
136     * Existing keys are updated. Others are added. A value of {@code null}
137     * deletes the key.
138     *
139     * @param key The key of the tag to insert.
140     * @param value The value of the tag to insert.
141     */
142    public void put(String key, String value) {
143        commitPendingEdit();
144        doPut(key, value);
145        setDirty(true);
146        fireTableDataChanged();
147    }
148
149    /**
150     * Inserts/updates/deletes all tags from {@code map}.
151     * <p>
152     * Existing keys are updated. Others are added. A value of {@code null}
153     * deletes the key.
154     *
155     * @param map a map of tags to insert or update
156     */
157    public void putAll(Map<String, String> map) {
158        commitPendingEdit();
159        map.forEach(this::doPut);
160        setDirty(true);
161        fireTableDataChanged();
162    }
163
164    /**
165     * Inserts all tags from a {@code DataSet}.
166     *
167     * @param dataSet The DataSet to take tags from.
168     */
169    public void putAll(DataSet dataSet) {
170        if (dataSet != null) {
171            putAll(dataSet.getChangeSetTags());
172            put(COMMENT, addHashTagsFromDataSet(getValue(COMMENT), dataSet));
173        }
174    }
175
176    /**
177     * Determines if the key is "comment" or "source".
178     * @param key changeset key
179     * @return {@code true} if the key is "comment" or "source"
180     * @since 18283
181     */
182    public static boolean isCommentOrSource(String key) {
183        return COMMENT.equals(key) || SOURCE.equals(key);
184    }
185}