001/* 002 * JGrapes Event Driven Framework 003 * Copyright (C) 2022,2023 Michael N. Lipp 004 * 005 * This program is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Affero General Public License as published by 007 * the Free Software Foundation; either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, but 011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public 013 * License for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License 016 * along with this program; if not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jgrapes.mail; 020 021import jakarta.mail.AuthenticationFailedException; 022import jakarta.mail.Authenticator; 023import jakarta.mail.Folder; 024import jakarta.mail.FolderClosedException; 025import jakarta.mail.Message; 026import jakarta.mail.MessagingException; 027import jakarta.mail.NoSuchProviderException; 028import jakarta.mail.PasswordAuthentication; 029import jakarta.mail.Session; 030import jakarta.mail.Store; 031import jakarta.mail.event.ConnectionEvent; 032import jakarta.mail.event.ConnectionListener; 033import jakarta.mail.event.MessageCountAdapter; 034import jakarta.mail.event.MessageCountEvent; 035import jakarta.mail.event.StoreEvent; 036import jakarta.mail.event.StoreListener; 037import java.io.IOException; 038import java.time.Duration; 039import java.util.ArrayList; 040import java.util.Arrays; 041import java.util.HashMap; 042import java.util.HashSet; 043import java.util.List; 044import java.util.Map; 045import java.util.Optional; 046import java.util.Properties; 047import java.util.Set; 048import java.util.function.Consumer; 049import java.util.logging.Level; 050import org.eclipse.angus.mail.imap.IMAPFolder; 051import org.eclipse.angus.mail.imap.IdleManager; 052import org.jgrapes.core.Channel; 053import org.jgrapes.core.Components; 054import org.jgrapes.core.Components.Timer; 055import org.jgrapes.core.Event; 056import org.jgrapes.core.EventPipeline; 057import org.jgrapes.core.Subchannel; 058import org.jgrapes.core.annotation.Handler; 059import org.jgrapes.io.events.Closed; 060import org.jgrapes.io.events.ConnectError; 061import org.jgrapes.io.events.IOError; 062import org.jgrapes.io.events.Opening; 063import org.jgrapes.mail.events.MailFoldersUpdated; 064import org.jgrapes.mail.events.MailMonitorOpened; 065import org.jgrapes.mail.events.OpenMailMonitor; 066import org.jgrapes.mail.events.UpdateMailFolders; 067import org.jgrapes.util.Password; 068 069/** 070 * A component that opens mail stores and monitors mail folders for 071 * mails. After establishing a connection to a store and selected 072 * folders (see {@link #onOpenMailMonitor(OpenMailMonitor, Channel)}), 073 * the existing and all subsequently arriving mails will be sent 074 * downstream using {@link MailFoldersUpdated} events. 075 * 076 * This implementation uses the {@link IdleManager}. The 077 * {@link IdleManager} works only if its {@link IdleManager#watch} 078 * method is invoked (for a folder) after any operation on that folder. 079 * Note that operations such as e.g. setting the deleted flag of 080 * a message is also an operation on a folder. 081 * 082 * Folders are updated in response to an {@link UpdateMailFolders} event 083 * or when the store signals the arrival of new messages. Information 084 * about the folders is delivered by a {@link MailFoldersUpdated} event. 085 * Folders may be freely used while handling the event, because the 086 * folders will be re-registered with the {@link IdleManager} 087 * when the {@link MailFoldersUpdated} event completes. 088 * Any usage of folders independent of handling the events mentioned 089 * will result in a loss of the monitor function. 090 * 091 * If required, the monitor function may be reestablished any time 092 * by firing a {@link UpdateMailFolders} event for the folders used. 093 */ 094@SuppressWarnings({ "PMD.CouplingBetweenObjects", 095 "PMD.AvoidSynchronizedStatement" }) 096public class MailMonitor extends MailConnectionManager< 097 MailMonitor.MonitorChannel, OpenMailMonitor> { 098 099 private Duration maxIdleTime = Duration.ofMinutes(25); 100 private static IdleManager idleManager; 101 private final EventPipeline retrievals = newEventPipeline(); 102 103 /** 104 * Creates a new server using the given channel. 105 * 106 * @param componentChannel the component's channel 107 */ 108 public MailMonitor(Channel componentChannel) { 109 super(componentChannel); 110 } 111 112 @Override 113 protected boolean connectionsGenerate() { 114 return true; 115 } 116 117 /** 118 * Sets the maximum idle time. A running {@link IMAPFolder#idle()} 119 * is terminated and renewed after this time. Defaults to 25 minutes. 120 * 121 * @param maxIdleTime the new max idle time 122 */ 123 public MailMonitor setMaxIdleTime(Duration maxIdleTime) { 124 this.maxIdleTime = maxIdleTime; 125 return this; 126 } 127 128 /** 129 * Returns the max idle time. 130 * 131 * @return the duration 132 */ 133 public Duration maxIdleTime() { 134 return maxIdleTime; 135 } 136 137 /** 138 * Configure the component. Currently, only max idle time 139 * is supported. 140 * 141 * @param values the values 142 */ 143 @Override 144 protected void configureComponent(Map<String, String> values) { 145 Optional.ofNullable(values.get("maxIdleTime")) 146 .map(Integer::parseInt).map(Duration::ofSeconds) 147 .ifPresent(this::setMaxIdleTime); 148 } 149 150 /** 151 * Open a store as specified by the event and monitor the folders 152 * (also specified by the event). Information about all existing 153 * and all subsequently arriving mails will be signaled downstream 154 * using {@link MailFoldersUpdated} events. 155 * 156 * @param event the event 157 * @param channel the channel 158 */ 159 @Handler 160 public void onOpenMailMonitor(OpenMailMonitor event, Channel channel) { 161 Properties sessionProps = new Properties(mailProps); 162 sessionProps.putAll(event.mailProperties()); 163 sessionProps.put("mail.imap.usesocketchannels", true); 164 Session session = Session.getInstance(sessionProps, 165 // Workaround for class loading problem in OSGi with j.m. 2.1. 166 // Authenticator's classpath allows accessing provider's service. 167 // See https://github.com/eclipse-ee4j/mail/issues/631 168 new Authenticator() { 169 @Override 170 protected PasswordAuthentication 171 getPasswordAuthentication() { 172 return new PasswordAuthentication( 173 sessionProps.getProperty("mail.user"), 174 new String( 175 event.password().or(MailMonitor.this::password) 176 .map(Password::password).orElse(new char[0]))); 177 } 178 }); 179 180 try { 181 synchronized (MailMonitor.class) { 182 // Cannot be created earlier, need session. 183 if (idleManager == null) { 184 idleManager = new IdleManager(session, 185 Components.defaultExecutorService()); 186 } 187 } 188 new MonitorChannel(event, channel, session.getStore(), 189 sessionProps.getProperty("mail.user"), 190 event.password().or(this::password).orElse(null)); 191 } catch (NoSuchProviderException e) { 192 fire(new ConnectError(event, "Cannot create store.", e)); 193 } catch (IOException e) { 194 fire(new IOError(event, "Cannot create resource.", e)); 195 } 196 } 197 198 /** 199 * Retrieves the folders specified in the event. 200 * 201 * @param event the event 202 * @param channel the channel 203 */ 204 @Handler 205 public void onUpdateFolders(UpdateMailFolders event, MailChannel channel) { 206 if (!connections.contains(channel)) { 207 return; 208 } 209 // This can take very long. 210 retrievals 211 .submit(() -> ((MonitorChannel) channel).onUpdateFolders(event)); 212 } 213 214 /** 215 * The Enum ChannelState. 216 */ 217 @SuppressWarnings({ "PMD.FieldNamingConventions", 218 "PMD.PublicMemberInNonPublicType" }) 219 private enum ChannelState { 220 Opening { 221 @Override 222 public boolean isOpening() { 223 return true; 224 } 225 }, 226 Open { 227 @Override 228 public boolean isOpen() { 229 return true; 230 } 231 }, 232 Reopening { 233 @Override 234 public boolean isOpening() { 235 return true; 236 } 237 }, 238 Reopened { 239 @Override 240 public boolean isOpen() { 241 return true; 242 } 243 }, 244 Closing, 245 Closed; 246 247 /** 248 * Checks if is open. 249 * 250 * @return true, if is open 251 */ 252 public boolean isOpen() { 253 return false; 254 } 255 256 /** 257 * Checks if is opening. 258 * 259 * @return true, if is opening 260 */ 261 public boolean isOpening() { 262 return false; 263 } 264 } 265 266 /** 267 * The specific implementation of the {@link MailChannel}. 268 */ 269 @SuppressWarnings("PMD.PublicMemberInNonPublicType") 270 protected class MonitorChannel extends 271 MailConnectionManager<MailMonitor.MonitorChannel, 272 OpenMailMonitor>.AbstractMailChannel 273 implements ConnectionListener, StoreListener { 274 275 private final EventPipeline requestPipeline; 276 private ChannelState state = ChannelState.Opening; 277 private final Store store; 278 private final String user; 279 private final Password password; 280 private final String[] subscribed; 281 @SuppressWarnings("PMD.UseConcurrentHashMap") 282 private final Map<String, Folder> folderCache = new HashMap<>(); 283 private final Timer idleTimer; 284 285 /** 286 * Instantiates a new monitor channel. 287 * 288 * @param event the event that triggered the creation 289 * @param mainChannel the main channel (of this {@link Subchannel}) 290 * @param store the store 291 * @param user the user 292 * @param password the password 293 */ 294 @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") 295 public MonitorChannel(OpenMailMonitor event, Channel mainChannel, 296 Store store, String user, Password password) { 297 super(event, mainChannel); 298 this.store = store; 299 this.user = user; 300 this.password = password; 301 this.subscribed = event.folderNames(); 302 requestPipeline = event.processedBy().get(); 303 store.addConnectionListener(this); 304 store.addStoreListener(this); 305 idleTimer = Components.schedule(t -> { 306 requestPipeline.fire(new UpdateMailFolders(), this); 307 }, maxIdleTime); 308 connect(t -> downPipeline().fire(new ConnectError(event, t), 309 mainChannel)); 310 } 311 312 /** 313 * Attempt connections until connected. Attempts are stopped 314 * if it is the first time that the connection is to be 315 * established and the error indicates that the connection 316 * will never succeed (e.g. due to an authentication 317 * problem). 318 * 319 * @param onOpenFailed the on open failed 320 */ 321 private void connect(Consumer<Throwable> onOpenFailed) { 322 synchronized (this) { 323 if (state.isOpen()) { 324 return; 325 } 326 activeEventPipeline().executorService().submit(() -> { 327 while (state.isOpening()) { 328 try { 329 attemptConnect(onOpenFailed); 330 } catch (InterruptedException e) { 331 break; 332 } 333 } 334 }); 335 } 336 } 337 338 /** 339 * Single connection attempt. 340 * 341 * @param onOpenFailed the on open failed 342 * @throws InterruptedException the interrupted exception 343 */ 344 @SuppressWarnings({ "PMD.AvoidInstanceofChecksInCatchClause" }) 345 private void attemptConnect(Consumer<Throwable> onOpenFailed) 346 throws InterruptedException { 347 try { 348 store.connect(user, new String(password.password())); 349 synchronized (this) { 350 if (state == ChannelState.Opening) { 351 state = ChannelState.Open; 352 } else { 353 state = ChannelState.Reopened; 354 } 355 } 356 } catch (MessagingException e) { 357 synchronized (this) { 358 if (state == ChannelState.Opening 359 && (e instanceof AuthenticationFailedException 360 || e instanceof NoSuchProviderException)) { 361 logger.log(Level.WARNING, 362 "Connecting to store failed, closing.", e); 363 state = ChannelState.Closed; 364 super.close(); 365 if (onOpenFailed != null) { 366 onOpenFailed.accept(e); 367 } 368 return; 369 } 370 } 371 logger.log(Level.WARNING, 372 "(Re)connecting to store failed, retrying.", e); 373 Thread.sleep(5000); 374 } 375 } 376 377 /** 378 * Close the connection to the store. 379 */ 380 @Override 381 public void close() { 382 synchronized (this) { 383 if (state == ChannelState.Closing 384 || state == ChannelState.Closed) { 385 return; 386 } 387 state = ChannelState.Closing; 388 } 389 390 idleTimer.cancel(); 391 try { 392 // Initiate close, callback will inform downstream components. 393 store.close(); 394 } catch (MessagingException e) { 395 // According to the documentation, the listeners should 396 // be invoked nevertheless. 397 logger.log(Level.WARNING, "Cannot close connection properly.", 398 e); 399 } 400 } 401 402 /** 403 * Callback from store.connect is the connection is successful. 404 * 405 * @param event the event 406 */ 407 @Override 408 public void opened(ConnectionEvent event) { 409 folderCache.clear(); 410 if (state == ChannelState.Reopened) { 411 // This is a re-open, only retrieve messages. 412 requestPipeline.fire(new UpdateMailFolders(), this); 413 return; 414 } 415 // (1) Opening, (2) Opened, (3) start retrieving mails 416 downPipeline().fire(Event.onCompletion(new Opening<Void>(), 417 o -> downPipeline().fire( 418 Event.onCompletion( 419 new MailMonitorOpened(openEvent(), store), 420 p -> requestPipeline 421 .fire(new UpdateMailFolders(), this)), 422 this)), 423 this); 424 } 425 426 /** 427 * According to the documentation, 428 * {@link ConnectionEvent#DISCONNECTED} is currently not 429 * used. It's implemented nevertheless and called explicitly. 430 * 431 * @param event the event or `null` if called explicitly 432 */ 433 @Override 434 public void disconnected(ConnectionEvent event) { 435 synchronized (this) { 436 folderCache.clear(); 437 if (state.isOpen()) { 438 state = ChannelState.Reopening; 439 connect(null); 440 } 441 } 442 } 443 444 /** 445 * Callback that indicates the connection close, 446 * can be called any time by jakarta mail. 447 * 448 * Whether closing is intended (callback after a call to 449 * {@link #close}) can be checked by looking at the state. 450 * 451 * @param event the event 452 */ 453 @Override 454 public void closed(ConnectionEvent event) { 455 // Ignore if already closed. 456 if (state == ChannelState.Closed) { 457 return; 458 } 459 460 // Handle involuntary close by reopening. 461 if (state != ChannelState.Closing) { 462 disconnected(event); 463 return; 464 } 465 466 // Cleanup and remove channel. 467 synchronized (this) { 468 state = ChannelState.Closed; 469 folderCache.clear(); 470 } 471 downPipeline().fire(new Closed<>(), this); 472 super.close(); 473 } 474 475 @Override 476 public void notification(StoreEvent event) { 477 if (event.getMessage().contains("SocketException")) { 478 logger.fine(() -> "Problem with store: " + event.getMessage()); 479 if (store.isConnected()) { 480 logger.fine(() -> "Updating folders to resume"); 481 requestPipeline.fire(new UpdateMailFolders(), this); 482 return; 483 } 484 logger.fine(() -> "Reconnecting to resume"); 485 disconnected(null); 486 } 487 } 488 489 /** 490 * Retrieve the new messages from the folders specified in the 491 * event. 492 * 493 * @param event 494 */ 495 public void onUpdateFolders(UpdateMailFolders event) { 496 List<Folder> folders = new ArrayList<>(); 497 List<Message> newMsgs = new ArrayList<>(); 498 if (store.isConnected()) { 499 Set<String> folderNames 500 = new HashSet<>(Arrays.asList(subscribed)); 501 if (event.folderNames().length > 0) { 502 folderNames.retainAll(Arrays.asList(event.folderNames())); 503 } 504 try { 505 for (var folderName : folderNames) { 506 @SuppressWarnings("PMD.CloseResource") 507 Folder folder = getFolder(folderName); 508 if (folder == null) { 509 continue; 510 } 511 folders.add(folder); 512 } 513 } catch (FolderClosedException e) { 514 disconnected(null); 515 } 516 } else { 517 disconnected(null); 518 } 519 event.setResult(folders); 520 Event.onCompletion(event, e -> downPipeline().fire(Event 521 .onCompletion(new MailFoldersUpdated(folders, newMsgs), 522 this::refreshWatches), 523 this)); 524 } 525 526 @SuppressWarnings({ "PMD.GuardLogStatement", "PMD.CloseResource" }) 527 private Folder getFolder(String folderName) 528 throws FolderClosedException { 529 synchronized (folderCache) { 530 Folder folder = folderCache.get(folderName); 531 if (folder != null) { 532 return folder; 533 } 534 try { 535 folder = store.getFolder(folderName); 536 if (folder == null || !folder.exists()) { 537 logger.fine(() -> "No folder \"" + folderName 538 + "\" in store " + store); 539 return null; 540 } 541 folder.open(Folder.READ_WRITE); 542 folderCache.put(folderName, folder); 543 // Add MessageCountListener to listen for new messages. 544 folder.addMessageCountListener(new MessageCountAdapter() { 545 @Override 546 public void 547 messagesAdded(MessageCountEvent countEvent) { 548 retrievals.submit("UpdateFolder", 549 () -> updateFolders(countEvent)); 550 } 551 552 @Override 553 public void 554 messagesRemoved(MessageCountEvent countEvent) { 555 retrievals.submit("UpdateFolder", 556 () -> updateFolders(countEvent)); 557 } 558 }); 559 return folder; 560 } catch (FolderClosedException e) { 561 throw e; 562 } catch (MessagingException e) { 563 logger.log(Level.FINE, 564 "Cannot open folder: " + e.getMessage(), e); 565 } 566 return null; 567 } 568 } 569 570 private void updateFolders(MessageCountEvent event) { 571 List<Message> newMsgs = new ArrayList<>(); 572 if (event.getType() == MessageCountEvent.ADDED) { 573 newMsgs.addAll(Arrays.asList(event.getMessages())); 574 } else if (event.getType() != MessageCountEvent.REMOVED) { 575 return; 576 } 577 downPipeline().fire( 578 Event.onCompletion( 579 new MailFoldersUpdated( 580 new ArrayList<>(folderCache.values()), newMsgs), 581 this::refreshWatches), 582 this); 583 } 584 585 /** 586 * Registers the folders from which messages have been received 587 * with the {@link IdleManager}. 588 * 589 * @param event the event 590 */ 591 @SuppressWarnings("PMD.CloseResource") 592 private void refreshWatches(MailFoldersUpdated event) { 593 if (!state.isOpen()) { 594 return; 595 } 596 for (Folder folder : event.folders()) { 597 try { 598 idleManager.watch(getFolder(folder.getFullName())); 599 } catch (MessagingException e) { 600 logger.log(Level.WARNING, "Cannot watch folder.", 601 e); 602 } 603 } 604 idleTimer.reschedule(maxIdleTime); 605 } 606 } 607 608 @Override 609 public String toString() { 610 return Components.objectName(this); 611 } 612 613}