log.info("Connecting to store/floder...");
final Session session = Session.getInstance(options.genProperties());
session.setDebug(options.isDebug());
final URLName imapUrlName = options.genImapUrlName();
store = (IMAPStore) session.getStore(imapUrlName);
final InternalConnectionListener connectionListener = new InternalConnectionListener();
//store.addConnectionListener(connectionListener);
store.connect(imapUrlName.getHost(), imapUrlName.getPort(), imapUrlName.getUsername(), imapUrlName.getPassword());
mainFolder = (IMAPFolder) store.getFolder(options.getImapFolder());
mainFolder.addConnectionListener(connectionListener);
mainFolder.open(Folder.READ_ONLY);
mainFolder.addMessageCountListener(new MessageCountAdapter() {
@Override
public void messagesAdded(MessageCountEvent event) {
log.debug("Incoming messages...");
try {
if (listeners.isEmpty()) {
log.warn("No listeners available for executing remote commands");
return;
}
final Message[] msgs = event.getMessages();
IMAPMessage msg;
for (final Message rmsg : msgs) {
if (!(rmsg instanceof IMAPMessage)) {
log.info(String.format("Expected %1$s, but received %2$s subject: %3$s",
IMAPMessage.class.getSimpleName(), rmsg.getClass().getSimpleName(), rmsg.getSubject()));
continue;
}
msg = (IMAPMessage) rmsg;
final Address[] froms = msg.getFrom();
if (hasCommandPermission(froms)) {
final StringBuffer errorMessages = new StringBuffer();
final List<Command> commands = getValidCommands(msg, errorMessages);
final Set<String> destinations = getValidCommandDestinations(msg, errorMessages);
if (errorMessages.length() > 0) {
if (log.isInfoEnabled()) {
log.info(String.format("Invalid command(s) received from: %1$s", Arrays.toString(froms)));
}
sendReply(msg, errorMessages.toString());
return;
}
if (log.isInfoEnabled()) {
log.info(String.format("Received raw commands: %1$s from: %2$s",
Arrays.toString(commands.toArray()), Arrays.toString(froms)));
}
final Thread newThread = new Thread(getThreadName(msg.getMessageID())) {
@Override
public void run() {
final EmailEvent event = new EmailEvent(EmailEvent.Type.EXECUTE_COMMAND, commands,
froms, destinations);
for (final IEmailListener listener : listeners) {
listener.handle(event);
}
}
};
newThread.start();
} else if (log.isInfoEnabled()) {
log.info(String.format("Received an email message from %1$s, but they do not have permission to execute commands",
Arrays.toString(froms)));
}
}
} catch (Exception e) {
log.error("Error when processing incoming message", e);
}
}
});
log.info("Connected to " + imapUrlName.getHost() + " waiting for messages...");
// when idle (blocking) gets interrupted (by host, sending an email, getting message content, etc.)
// try to reinstate the idle process, if that fails (usually due to a closed folder) try to reconnect
while (runIt) {
mainFolder.idle();
if (runIt) {