001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.net.Authenticator.RequestorType;
007import java.util.concurrent.Executors;
008import java.util.concurrent.ScheduledExecutorService;
009import java.util.concurrent.ScheduledFuture;
010import java.util.concurrent.TimeUnit;
011
012import org.openstreetmap.josm.data.UserIdentityManager;
013import org.openstreetmap.josm.data.oauth.OAuthVersion;
014import org.openstreetmap.josm.data.osm.UserInfo;
015import org.openstreetmap.josm.data.preferences.BooleanProperty;
016import org.openstreetmap.josm.data.preferences.IntegerProperty;
017import org.openstreetmap.josm.gui.ExceptionDialogUtil;
018import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
019import org.openstreetmap.josm.io.auth.CredentialsAgentException;
020import org.openstreetmap.josm.io.auth.CredentialsAgentResponse;
021import org.openstreetmap.josm.io.auth.CredentialsManager;
022import org.openstreetmap.josm.io.auth.JosmPreferencesCredentialAgent;
023import org.openstreetmap.josm.spi.preferences.Config;
024import org.openstreetmap.josm.tools.Logging;
025import org.openstreetmap.josm.tools.Utils;
026
027/**
028 * Notifies user periodically of new received (unread) messages
029 * @since 6349
030 */
031public final class MessageNotifier {
032
033    private MessageNotifier() {
034        // Hide default constructor for utils classes
035    }
036
037    /**
038     * Called when new new messages are detected.
039     * @since 12766
040     */
041    @FunctionalInterface
042    public interface NotifierCallback {
043        /**
044         * Perform the actual notification of new messages.
045         * @param userInfo the new user information, that includes the number of unread messages
046         */
047        void notifyNewMessages(UserInfo userInfo);
048    }
049
050    private static volatile NotifierCallback callback;
051
052    /**
053     * Sets the {@link NotifierCallback} responsible of notifying the user when new messages are received.
054     * @param notifierCallback the new {@code NotifierCallback}
055     */
056    public static void setNotifierCallback(NotifierCallback notifierCallback) {
057        callback = notifierCallback;
058    }
059
060    /** Property defining if this task is enabled or not */
061    public static final BooleanProperty PROP_NOTIFIER_ENABLED = new BooleanProperty("message.notifier.enabled", true);
062    /** Property defining the update interval in minutes */
063    public static final IntegerProperty PROP_INTERVAL = new IntegerProperty("message.notifier.interval", 5);
064
065    private static final ScheduledExecutorService EXECUTOR =
066            Executors.newSingleThreadScheduledExecutor(Utils.newThreadFactory("message-notifier-%d", Thread.NORM_PRIORITY));
067
068    private static final Runnable WORKER = new Worker();
069
070    private static volatile ScheduledFuture<?> task;
071
072    private static final class Worker implements Runnable {
073
074        private int lastUnreadCount;
075        private long lastTimeInMillis;
076
077        @Override
078        public void run() {
079            try {
080                long currentTime = System.currentTimeMillis();
081                // See #14671 - Make sure we don't run the API call many times after system wakeup
082                if (currentTime >= lastTimeInMillis + TimeUnit.MINUTES.toMillis(PROP_INTERVAL.get())) {
083                    lastTimeInMillis = currentTime;
084                    final UserInfo userInfo = new OsmServerUserInfoReader().fetchUserInfo(NullProgressMonitor.INSTANCE,
085                            tr("get number of unread messages"));
086                    final int unread = userInfo.getUnreadMessages();
087                    if (unread > 0 && unread != lastUnreadCount) {
088                        callback.notifyNewMessages(userInfo);
089                        lastUnreadCount = unread;
090                    }
091                }
092            } catch (OsmApiException e) {
093                // We want to explicitly display message to user in some cases like when he has been blocked (#17722)
094                ExceptionDialogUtil.explainOsmTransferException(e);
095            } catch (OsmTransferException e) {
096                // But not message for random network or API issues (like in #17929)
097                Logging.warn(e);
098            }
099        }
100    }
101
102    /**
103     * Starts the message notifier task if not already started and if user is fully identified
104     */
105    public static void start() {
106        int interval = PROP_INTERVAL.get();
107        if (NetworkManager.isOffline(OnlineResource.OSM_API)) {
108            Logging.info(OfflineAccessException.forResource(tr("Message notifier")).getMessage());
109        } else if (!isRunning() && interval > 0 && isUserEnoughIdentified()) {
110            task = EXECUTOR.scheduleAtFixedRate(WORKER, 0, interval, TimeUnit.MINUTES);
111            Logging.info("Message notifier active (checks every "+interval+" minute"+(interval > 1 ? "s" : "")+')');
112        }
113    }
114
115    /**
116     * Stops the message notifier task if started
117     */
118    public static void stop() {
119        if (isRunning()) {
120            task.cancel(false);
121            Logging.info("Message notifier inactive");
122            task = null;
123        }
124    }
125
126    /**
127     * Determines if the message notifier is currently running
128     * @return {@code true} if the notifier is running, {@code false} otherwise
129     */
130    public static boolean isRunning() {
131        return task != null;
132    }
133
134    /**
135     * Determines if user set enough information in JOSM preferences to make the request to OSM API without
136     * prompting him for a password.
137     * @return {@code true} if user chose an OAuth token or supplied both its username and password, {@code false otherwise}
138     */
139    public static boolean isUserEnoughIdentified() {
140        UserIdentityManager identManager = UserIdentityManager.getInstance();
141        if (identManager.isFullyIdentified()) {
142            return true;
143        } else {
144            CredentialsManager credManager = CredentialsManager.getInstance();
145            try {
146                if (JosmPreferencesCredentialAgent.class.equals(credManager.getCredentialsAgentClass())) {
147                    if (OsmApi.isUsingOAuth(OAuthVersion.OAuth20) || OsmApi.isUsingOAuth(OAuthVersion.OAuth21)) {
148                        return credManager.lookupOAuthAccessToken(OsmApi.getOsmApi().getHost()) != null;
149                    } else if (OsmApi.isUsingOAuth()) {
150                        // Ensure we do not forget to update this section
151                        throw new IllegalStateException("Unknown oauth version: " + OsmApi.getAuthMethod());
152                    } else {
153                        String username = Config.getPref().get("osm-server.username", null);
154                        String password = Config.getPref().get("osm-server.password", null);
155                        return !Utils.isEmpty(username) && !Utils.isEmpty(password);
156                    }
157                } else {
158                    CredentialsAgentResponse credentials = credManager.getCredentials(
159                            RequestorType.SERVER, OsmApi.getOsmApi().getHost(), false);
160                    if (credentials != null) {
161                        String username = credentials.getUsername();
162                        char[] password = credentials.getPassword();
163                        return !Utils.isEmpty(username) && password != null && password.length > 0;
164                    }
165                }
166            } catch (CredentialsAgentException e) {
167                Logging.log(Logging.LEVEL_WARN, "Unable to get credentials:", e);
168            }
169        }
170        return false;
171    }
172}