🔀 Merge remote-tracking branch 'origin/master'
[xudocci.git] / src / main / java / net / pterodactylus / xdcc / core / Core.java
index 5ec21cf..8ef074c 100644 (file)
 package net.pterodactylus.xdcc.core;
 
 import static java.lang.String.format;
+import static java.util.stream.Collectors.toSet;
 import static net.pterodactylus.irc.event.ChannelNotJoined.Reason.banned;
 import static net.pterodactylus.irc.event.ChannelNotJoined.Reason.inviteOnly;
 import static net.pterodactylus.irc.event.ChannelNotJoined.Reason.registeredNicknamesOnly;
 import static net.pterodactylus.irc.util.MessageCleaner.getDefaultInstance;
-import static net.pterodactylus.xdcc.data.Channel.TO_NETWORK;
 import static net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
 
 import java.io.File;
@@ -30,6 +30,8 @@ import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
+import java.time.Duration;
+import java.time.Instant;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
@@ -110,6 +112,7 @@ public class Core extends AbstractExecutionThreadService {
        /** The logger. */
        private static final Logger logger = Logger.getLogger(Core.class.getName());
 
+       private final Instant startup = Instant.now();
        private final Object syncObject = new Object();
        /** The event bus. */
        private final EventBus eventBus;
@@ -183,7 +186,7 @@ public class Core extends AbstractExecutionThreadService {
         * @return All defined networks
         */
        public Collection<Network> networks() {
-               return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
+               return FluentIterable.from(channels).transform(Channel::network).toSet();
        }
 
        /**
@@ -196,8 +199,11 @@ public class Core extends AbstractExecutionThreadService {
                        Network network = entry.getKey();
                        Collection<Bot> bots = networkBots.row(network).values();
                        int packCount = bots.stream().mapToInt((bot) -> bot.packs().size()).reduce((a, b) -> a + b).orElse(0);
-                       return new ConnectedNetwork(network, entry.getValue().hostname(),
-                                       entry.getValue().port(), entry.getValue().nickname(),
+                       Connection connection = entry.getValue();
+                       return new ConnectedNetwork(network, connection.hostname(),
+                                       connection.port(),
+                                       connection.getUptime().orElse(Duration.ofSeconds(0)),
+                                       connection.nickname(),
                                        channels.stream()
                                                        .filter((channel) -> channel.network()
                                                                        .equals(network))
@@ -258,6 +264,10 @@ public class Core extends AbstractExecutionThreadService {
                return downloads.values();
        }
 
+       public Duration getUptime() {
+               return Duration.between(startup, Instant.now());
+       }
+
        //
        // ACTIONS
        //
@@ -329,13 +339,6 @@ public class Core extends AbstractExecutionThreadService {
                        return;
                }
 
-               /* get connection. */
-               Connection connection = networkConnections.get(bot.network());
-               if (connection == null) {
-                       /* request for unknown network? */
-                       return;
-               }
-
                /* stop the DCC receiver. */
                if (download.get().dccReceiver() != null) {
                        download.get().dccReceiver().stop();
@@ -344,6 +347,13 @@ public class Core extends AbstractExecutionThreadService {
                        downloads.remove(pack.name(), download.get());
                }
 
+               /* get connection. */
+               Connection connection = networkConnections.get(bot.network());
+               if (connection == null) {
+                       /* request for unknown network? */
+                       return;
+               }
+
                /* remove the request from the bot, too. */
                try {
                        connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
@@ -401,7 +411,7 @@ public class Core extends AbstractExecutionThreadService {
                                        .map(Channel::network)
                                        .distinct()
                                        .filter((network) -> !networkConnections.containsKey(network))
-                                       .collect(Collectors.toSet());
+                                       .collect(toSet());
 
                        if (missingNetworks.isEmpty()) {
                                if (!missingChannels.isEmpty()) {
@@ -435,7 +445,7 @@ public class Core extends AbstractExecutionThreadService {
                                continue;
                        }
                        if (firstNetwork.get().getKey() > System.currentTimeMillis()) {
-                               eventBus.post(new GenericMessage(String.format("Waiting %d minutes to connect to %s...", TimeUnit.MILLISECONDS.toMinutes(firstNetwork.get().getKey() - System.currentTimeMillis()), firstNetwork.get().getValue().name())));
+                               eventBus.post(new GenericMessage(String.format("Will connect to %2$s at %1$tH:%1$tM...", firstNetwork.get().getKey(), firstNetwork.get().getValue().name())));
                                synchronized (syncObject) {
                                        try {
                                                syncObject.wait(firstNetwork.get().getKey() - System.currentTimeMillis());
@@ -498,14 +508,14 @@ public class Core extends AbstractExecutionThreadService {
         *              The connection to remove
         */
        private void removeConnection(Connection connection) {
+               logger.debug(String.format("Removing Connection %s...", connection));
                Optional<Network> network = getNetwork(connection);
                if (!network.isPresent()) {
+                       logger.debug(String.format("Connection %s did not belong to any network.", connection));
                        return;
                }
+               logger.debug(String.format("Connection %s belongs to network %s.", connection, network.get()));
                networkConnections.remove(network.get());
-               if (!connection.established()) {
-                       return;
-               }
 
                /* find all channels that need to be removed. */
                for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
@@ -514,7 +524,7 @@ public class Core extends AbstractExecutionThreadService {
                                if (!joinedChannel.network().equals(network.get())) {
                                        continue;
                                }
-
+                               logger.debug(String.format("Channel %s will be removed.", joinedChannel));
                                channelIterator.remove();
                        }
                }
@@ -653,7 +663,7 @@ public class Core extends AbstractExecutionThreadService {
                                .values().stream()
                                .filter(bot -> bot.channel()
                                                .equalsIgnoreCase(channel.get().name()))
-                               .collect(Collectors.toSet());
+                               .collect(toSet());
                botsToRemove.stream()
                                .forEach(bot -> networkBots.row(network.get())
                                                .remove(bot.name()));
@@ -661,7 +671,8 @@ public class Core extends AbstractExecutionThreadService {
                channelBanManager.ban(channel.get());
                if (channelNotJoined.reason() == registeredNicknamesOnly) {
                        eventBus.post(new GenericMessage(
-                                       format("Not trying to join %s anymore.", channel.get())));
+                                       format("%s requires nickname registration, suspending join for a day.",
+                                                       channel.get())));
                } else if (channelNotJoined.reason() == inviteOnly) {
                        eventBus.post(new GenericMessage(
                                        format("%s is invite-only, suspending join for a day.",
@@ -749,7 +760,7 @@ public class Core extends AbstractExecutionThreadService {
                                        "Kicked from %s by %s: %s",
                                        kickedFromChannel.channel(),
                                        kickedFromChannel.kicker(),
-                                       kickedFromChannel.reason().or("<unknown>")
+                                       kickedFromChannel.reason().orElse("<unknown>")
                        )));
                }
        }
@@ -876,38 +887,38 @@ public class Core extends AbstractExecutionThreadService {
        @Subscribe
        public void dccSendReceived(final DccSendReceived dccSendReceived) {
                final Optional<Network> network = getNetwork(dccSendReceived.connection());
+               eventBus.post(new GenericMessage(format("Got DCC Send from %s for %s.", dccSendReceived.source(), dccSendReceived.filename())));
                if (!network.isPresent()) {
                        return;
                }
+               eventBus.post(new GenericMessage("a"));
 
-               Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
-               if (packDownloads.isEmpty()) {
-                       /* unknown download, ignore. */
-                       return;
-               }
+               Set<Download> openDownloads = downloads.values().stream()
+                               .filter(download -> download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().orNull()))
+                               .filter(download -> download.dccReceiver() == null)
+                               .collect(toSet());
+               eventBus.post(new GenericMessage("b"));
 
-               /* check if it’s already downloading. */
-               Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
-               if (!runningDownloads.isEmpty()) {
-                       eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
+               if (openDownloads.isEmpty()) {
+                       /* I don't think we requested this. */
+                       eventBus.post(new GenericMessage(format("Ignoring offer for %s, no open download from %s.", dccSendReceived.filename(), dccSendReceived.source())));
                        return;
                }
+               eventBus.post(new GenericMessage("c"));
 
-               /* locate the correct download. */
-               Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
-
-                       @Override
-                       public boolean apply(Download download) {
-                               return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
-                       }
-               }).toSet();
-
-               /* we did not request this download. */
-               if (requestedDownload.isEmpty()) {
+               /* check if it’s already downloading. */
+               if (downloads.values().stream().anyMatch(download -> download.filename().equals(dccSendReceived.filename()) && download.dccReceiver() != null)) {
+                       eventBus.post(new GenericMessage(format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
                        return;
                }
-
-               Download download = requestedDownload.iterator().next();
+               eventBus.post(new GenericMessage("d"));
+
+               Download download = openDownloads.stream()
+                               .filter(it -> it.filename().equals(dccSendReceived.filename()))
+                               .findFirst()
+                               .orElse(openDownloads.iterator().next());
+               eventBus.post(new GenericMessage("e"));
+               eventBus.post(new GenericMessage(format("Downloading %s from %s as %s.", dccSendReceived.filename(), dccSendReceived.source(), download.filename())));
 
                /* check if the file already exists. */
                File outputFile = new File(temporaryDirectory, dccSendReceived.filename());