source: josm/trunk/src/org/openstreetmap/josm/io/MessageNotifier.java@ 12671

Last change on this file since 12671 was 12620, checked in by Don-vip, 7 years ago

see #15182 - deprecate all Main logging methods and introduce suitable replacements in Logging for most of them

  • Property svn:eol-style set to native
File size: 7.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.awt.GridBagLayout;
8import java.net.Authenticator.RequestorType;
9import java.util.concurrent.Executors;
10import java.util.concurrent.ScheduledExecutorService;
11import java.util.concurrent.ScheduledFuture;
12import java.util.concurrent.TimeUnit;
13
14import javax.swing.JLabel;
15import javax.swing.JOptionPane;
16import javax.swing.JPanel;
17
18import org.openstreetmap.josm.Main;
19import org.openstreetmap.josm.data.osm.UserInfo;
20import org.openstreetmap.josm.data.preferences.BooleanProperty;
21import org.openstreetmap.josm.data.preferences.IntegerProperty;
22import org.openstreetmap.josm.gui.JosmUserIdentityManager;
23import org.openstreetmap.josm.gui.Notification;
24import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
25import org.openstreetmap.josm.gui.util.GuiHelper;
26import org.openstreetmap.josm.gui.widgets.UrlLabel;
27import org.openstreetmap.josm.io.auth.CredentialsAgentException;
28import org.openstreetmap.josm.io.auth.CredentialsAgentResponse;
29import org.openstreetmap.josm.io.auth.CredentialsManager;
30import org.openstreetmap.josm.io.auth.JosmPreferencesCredentialAgent;
31import org.openstreetmap.josm.tools.GBC;
32import org.openstreetmap.josm.tools.Logging;
33import org.openstreetmap.josm.tools.Utils;
34
35/**
36 * Notifies user periodically of new received (unread) messages
37 * @since 6349
38 */
39public final class MessageNotifier {
40
41 private MessageNotifier() {
42 // Hide default constructor for utils classes
43 }
44
45 /** Property defining if this task is enabled or not */
46 public static final BooleanProperty PROP_NOTIFIER_ENABLED = new BooleanProperty("message.notifier.enabled", true);
47 /** Property defining the update interval in minutes */
48 public static final IntegerProperty PROP_INTERVAL = new IntegerProperty("message.notifier.interval", 5);
49
50 private static final ScheduledExecutorService EXECUTOR =
51 Executors.newSingleThreadScheduledExecutor(Utils.newThreadFactory("message-notifier-%d", Thread.NORM_PRIORITY));
52
53 private static final Runnable WORKER = new Worker();
54
55 private static volatile ScheduledFuture<?> task;
56
57 private static class Worker implements Runnable {
58
59 private int lastUnreadCount;
60 private long lastTimeInMillis;
61
62 @Override
63 public void run() {
64 try {
65 long currentTime = System.currentTimeMillis();
66 // See #14671 - Make sure we don't run the API call many times after system wakeup
67 if (currentTime >= lastTimeInMillis + TimeUnit.MINUTES.toMillis(PROP_INTERVAL.get())) {
68 lastTimeInMillis = currentTime;
69 final UserInfo userInfo = new OsmServerUserInfoReader().fetchUserInfo(NullProgressMonitor.INSTANCE,
70 tr("get number of unread messages"));
71 final int unread = userInfo.getUnreadMessages();
72 if (unread > 0 && unread != lastUnreadCount) {
73 GuiHelper.runInEDT(() -> {
74 JPanel panel = new JPanel(new GridBagLayout());
75 panel.add(new JLabel(trn("You have {0} unread message.", "You have {0} unread messages.", unread, unread)),
76 GBC.eol());
77 panel.add(new UrlLabel(Main.getBaseUserUrl() + '/' + userInfo.getDisplayName() + "/inbox",
78 tr("Click here to see your inbox.")), GBC.eol());
79 panel.setOpaque(false);
80 new Notification().setContent(panel)
81 .setIcon(JOptionPane.INFORMATION_MESSAGE)
82 .setDuration(Notification.TIME_LONG)
83 .show();
84 });
85 lastUnreadCount = unread;
86 }
87 }
88 } catch (OsmTransferException e) {
89 Logging.warn(e);
90 }
91 }
92 }
93
94 /**
95 * Starts the message notifier task if not already started and if user is fully identified
96 */
97 public static void start() {
98 int interval = PROP_INTERVAL.get();
99 if (Main.isOffline(OnlineResource.OSM_API)) {
100 Logging.info(tr("{0} not available (offline mode)", tr("Message notifier")));
101 } else if (!isRunning() && interval > 0 && isUserEnoughIdentified()) {
102 task = EXECUTOR.scheduleAtFixedRate(WORKER, 0, TimeUnit.MINUTES.toSeconds(interval), TimeUnit.SECONDS);
103 Logging.info("Message notifier active (checks every "+interval+" minute"+(interval > 1 ? "s" : "")+')');
104 }
105 }
106
107 /**
108 * Stops the message notifier task if started
109 */
110 public static void stop() {
111 if (isRunning()) {
112 task.cancel(false);
113 Logging.info("Message notifier inactive");
114 task = null;
115 }
116 }
117
118 /**
119 * Determines if the message notifier is currently running
120 * @return {@code true} if the notifier is running, {@code false} otherwise
121 */
122 public static boolean isRunning() {
123 return task != null;
124 }
125
126 /**
127 * Determines if user set enough information in JOSM preferences to make the request to OSM API without
128 * prompting him for a password.
129 * @return {@code true} if user chose an OAuth token or supplied both its username and password, {@code false otherwise}
130 */
131 public static boolean isUserEnoughIdentified() {
132 JosmUserIdentityManager identManager = JosmUserIdentityManager.getInstance();
133 if (identManager.isFullyIdentified()) {
134 return true;
135 } else {
136 CredentialsManager credManager = CredentialsManager.getInstance();
137 try {
138 if (JosmPreferencesCredentialAgent.class.equals(credManager.getCredentialsAgentClass())) {
139 if (OsmApi.isUsingOAuth()) {
140 return credManager.lookupOAuthAccessToken() != null;
141 } else {
142 String username = Main.pref.get("osm-server.username", null);
143 String password = Main.pref.get("osm-server.password", null);
144 return username != null && !username.isEmpty() && password != null && !password.isEmpty();
145 }
146 } else {
147 CredentialsAgentResponse credentials = credManager.getCredentials(
148 RequestorType.SERVER, OsmApi.getOsmApi().getHost(), false);
149 if (credentials != null) {
150 String username = credentials.getUsername();
151 char[] password = credentials.getPassword();
152 return username != null && !username.isEmpty() && password != null && password.length > 0;
153 }
154 }
155 } catch (CredentialsAgentException e) {
156 Logging.log(Logging.LEVEL_WARN, "Unable to get credentials:", e);
157 }
158 }
159 return false;
160 }
161}
Note: See TracBrowser for help on using the repository browser.