2 * XdccDownloader - Core.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.xdcc.core;
20 import static java.lang.String.format;
21 import static net.pterodactylus.irc.event.ChannelNotJoined.Reason.banned;
22 import static net.pterodactylus.irc.event.ChannelNotJoined.Reason.inviteOnly;
23 import static net.pterodactylus.irc.event.ChannelNotJoined.Reason.registeredNicknamesOnly;
24 import static net.pterodactylus.irc.util.MessageCleaner.getDefaultInstance;
25 import static net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
28 import java.io.FileNotFoundException;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.io.OutputStream;
32 import java.time.Duration;
33 import java.time.Instant;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.HashSet;
37 import java.util.Iterator;
38 import java.util.List;
40 import java.util.Map.Entry;
42 import java.util.TreeMap;
43 import java.util.concurrent.TimeUnit;
44 import java.util.function.Function;
45 import java.util.stream.Collectors;
47 import net.pterodactylus.irc.Connection;
48 import net.pterodactylus.irc.ConnectionFactory;
49 import net.pterodactylus.irc.DccReceiver;
50 import net.pterodactylus.irc.DefaultConnection;
51 import net.pterodactylus.irc.event.ChannelJoined;
52 import net.pterodactylus.irc.event.ChannelLeft;
53 import net.pterodactylus.irc.event.ChannelMessageReceived;
54 import net.pterodactylus.irc.event.ChannelNotJoined;
55 import net.pterodactylus.irc.event.ClientQuit;
56 import net.pterodactylus.irc.event.ConnectionClosed;
57 import net.pterodactylus.irc.event.ConnectionEstablished;
58 import net.pterodactylus.irc.event.ConnectionFailed;
59 import net.pterodactylus.irc.event.DccAcceptReceived;
60 import net.pterodactylus.irc.event.DccDownloadFailed;
61 import net.pterodactylus.irc.event.DccDownloadFinished;
62 import net.pterodactylus.irc.event.DccSendReceived;
63 import net.pterodactylus.irc.event.KickedFromChannel;
64 import net.pterodactylus.irc.event.NicknameChanged;
65 import net.pterodactylus.irc.event.PrivateMessageReceived;
66 import net.pterodactylus.irc.event.PrivateNoticeReceived;
67 import net.pterodactylus.irc.event.ReplyReceived;
68 import net.pterodactylus.irc.util.RandomNickname;
69 import net.pterodactylus.xdcc.core.event.BotAdded;
70 import net.pterodactylus.xdcc.core.event.CoreStarted;
71 import net.pterodactylus.xdcc.core.event.DownloadFailed;
72 import net.pterodactylus.xdcc.core.event.DownloadFinished;
73 import net.pterodactylus.xdcc.core.event.DownloadStarted;
74 import net.pterodactylus.xdcc.core.event.GenericError;
75 import net.pterodactylus.xdcc.core.event.GenericMessage;
76 import net.pterodactylus.xdcc.core.event.MessageReceived;
77 import net.pterodactylus.xdcc.data.Bot;
78 import net.pterodactylus.xdcc.data.Channel;
79 import net.pterodactylus.xdcc.data.ConnectedNetwork;
80 import net.pterodactylus.xdcc.data.Download;
81 import net.pterodactylus.xdcc.data.Network;
82 import net.pterodactylus.xdcc.data.Pack;
83 import net.pterodactylus.xdcc.data.Server;
85 import com.google.common.base.Optional;
86 import com.google.common.base.Predicate;
87 import com.google.common.collect.FluentIterable;
88 import com.google.common.collect.HashBasedTable;
89 import com.google.common.collect.HashMultimap;
90 import com.google.common.collect.ImmutableList;
91 import com.google.common.collect.ImmutableSet;
92 import com.google.common.collect.Lists;
93 import com.google.common.collect.Maps;
94 import com.google.common.collect.Multimap;
95 import com.google.common.collect.Sets;
96 import com.google.common.collect.Table;
97 import com.google.common.eventbus.EventBus;
98 import com.google.common.eventbus.Subscribe;
99 import com.google.common.io.Closeables;
100 import com.google.common.util.concurrent.AbstractExecutionThreadService;
101 import com.google.inject.Inject;
102 import org.apache.log4j.Logger;
105 * The core of XDCC Downloader.
107 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
109 public class Core extends AbstractExecutionThreadService {
112 private static final Logger logger = Logger.getLogger(Core.class.getName());
114 private final Instant startup = Instant.now();
115 private final Object syncObject = new Object();
116 /** The event bus. */
117 private final EventBus eventBus;
118 private final ConnectionFactory connectionFactory;
119 private final ChannelBanManager channelBanManager =
120 new ChannelBanManager();
121 private final ConnectionBackoff connectionBackoff = new ConnectionBackoff();
123 /** The temporary directory to download files to. */
124 private final String temporaryDirectory;
126 /** The directory to move finished downloads to. */
127 private final String finalDirectory;
129 /** The channels that should be monitored. */
130 private final Collection<Channel> channels = Sets.newHashSet();
132 /** The channels that are currentlymonitored. */
133 private final Collection<Channel> joinedChannels = Sets.newHashSet();
134 private final Set<Channel> channelsBeingJoined = new HashSet<>();
136 /** The channels that are joined but not configured. */
137 private final Collection<Channel> extraChannels = Sets.newHashSet();
139 /** The current network connections. */
140 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
142 /** The currently known bots. */
143 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
145 /** The current downloads. */
146 private final Multimap<String, Download> downloads = HashMultimap.create();
148 /** The current DCC receivers. */
149 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
152 * Creates a new core.
156 * @param temporaryDirectory
157 * The directory to download files to
158 * @param finalDirectory
159 * The directory to move finished files to
162 public Core(EventBus eventBus, ConnectionFactory connectionFactory, String temporaryDirectory, String finalDirectory) {
163 this.eventBus = eventBus;
164 this.connectionFactory = connectionFactory;
165 this.temporaryDirectory = temporaryDirectory;
166 this.finalDirectory = finalDirectory;
174 * Returns all currently known connections.
176 * @return All currently known connections
178 public Collection<Connection> connections() {
179 return networkConnections.values();
183 * Returns all defined networks.
185 * @return All defined networks
187 public Collection<Network> networks() {
188 return FluentIterable.from(channels).transform(Channel::network).toSet();
192 * Returns all connected networks.
194 * @return All connected networks
196 public Collection<ConnectedNetwork> connectedNetworks() {
197 return networkConnections.entrySet().stream().map((entry) -> {
198 Network network = entry.getKey();
199 Collection<Bot> bots = networkBots.row(network).values();
200 int packCount = bots.stream().mapToInt((bot) -> bot.packs().size()).reduce((a, b) -> a + b).orElse(0);
201 Connection connection = entry.getValue();
202 return new ConnectedNetwork(network, connection.hostname(),
204 connection.getUptime().orElse(Duration.ofSeconds(0)),
205 connection.nickname(),
207 .filter((channel) -> channel.network()
210 .collect(Collectors.<String>toList()),
211 extraChannels.stream()
212 .filter((channel) -> channel.network()
215 .collect(Collectors.<String>toList()),
216 bots.size(), packCount);
217 }).collect(Collectors.<ConnectedNetwork>toList());
221 * Returns all configured channels. Due to various circumstances, configured
222 * channels might not actually be joined.
224 * @return All configured channels
226 public Collection<Channel> channels() {
227 return ImmutableSet.copyOf(channels);
231 * Returns all currently joined channels.
233 * @return All currently joined channels
235 public Collection<Channel> joinedChannels() {
236 return ImmutableSet.copyOf(joinedChannels);
240 * Returns all currently joined channels that are not configured.
242 * @return All currently joined but not configured channels
244 public Collection<Channel> extraChannels() {
245 return ImmutableSet.copyOf(extraChannels);
249 * Returns all currently known bots.
251 * @return All currently known bots
253 public Collection<Bot> bots() {
254 return networkBots.values();
258 * Returns all currently running downloads.
260 * @return All currently running downloads
262 public Collection<Download> downloads() {
263 return downloads.values();
266 public Duration getUptime() {
267 return Duration.between(startup, Instant.now());
275 * Adds a channel to monitor.
278 * The channel to monitor
280 public void addChannel(Channel channel) {
281 channels.add(channel);
285 * Fetches the given pack from the given bot.
288 * The bot to fetch the pack from
292 public void fetch(Bot bot, Pack pack) {
293 Connection connection = networkConnections.get(bot.network());
294 if (connection == null) {
298 /* check if we are already downloading the file? */
299 if (downloads.containsKey(pack.name())) {
300 Collection<Download> packDownloads = downloads.get(pack.name());
301 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
302 if (!runningDownloads.isEmpty()) {
303 Download download = runningDownloads.iterator().next();
304 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
307 StringBuilder bots = new StringBuilder();
308 for (Download download : packDownloads) {
309 if (bots.length() > 0) {
312 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
314 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
317 Download download = new Download(bot, pack);
318 downloads.put(pack.name(), download);
321 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
322 } catch (IOException ioe1) {
323 logger.warn("Could not send message to bot!", ioe1);
328 * Cancels the download of the given pack from the given bot.
331 * The bot the pack is being downloaded from
333 * The pack being downloaded
335 public void cancelDownload(Bot bot, Pack pack) {
336 Optional<Download> download = getDownload(pack, bot);
337 if (!download.isPresent()) {
341 /* stop the DCC receiver. */
342 if (download.get().dccReceiver() != null) {
343 download.get().dccReceiver().stop();
345 /* remove download if it hasn’t started yet. */
346 downloads.remove(pack.name(), download.get());
349 /* get connection. */
350 Connection connection = networkConnections.get(bot.network());
351 if (connection == null) {
352 /* request for unknown network? */
356 /* remove the request from the bot, too. */
358 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
359 } catch (IOException ioe1) {
360 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
365 * Closes the given connection.
368 * The connection to close
370 public void closeConnection(Connection connection) {
373 } catch (IOException ioe1) {
379 // ABSTRACTIDLESERVICE METHODS
383 protected void startUp() {
384 for (Channel channel : channels) {
385 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
386 connectNetwork(channel.network());
389 /* notify listeners. */
390 eventBus.post(new CoreStarted(this));
394 protected void run() throws Exception {
395 while (isRunning()) {
397 Set<Channel> missingChannels = new HashSet<>();
398 for (Channel channel : channels) {
399 if (joinedChannels.contains(channel) || channelsBeingJoined.contains(channel)) {
402 if (channelBanManager.isBanned(channel)) {
405 if (!networkConnections.containsKey(channel.network()) || networkConnections.get(channel.network()).established()) {
406 missingChannels.add(channel);
409 Set<Network> missingNetworks = missingChannels.stream()
410 .map(Channel::network)
412 .filter((network) -> !networkConnections.containsKey(network))
413 .collect(Collectors.toSet());
415 if (missingNetworks.isEmpty()) {
416 if (!missingChannels.isEmpty()) {
417 for (Channel missingChannel : missingChannels) {
418 Network network = missingChannel.network();
419 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", missingChannel.name(), network)));
421 channelsBeingJoined.add(missingChannel);
422 networkConnections.get(network).joinChannel(missingChannel.name());
423 } catch (IOException ioe1) {
424 logger.warn(String.format("Could not join %s on %s!", missingChannel.name(), network.name()), ioe1);
428 synchronized (syncObject) {
430 syncObject.wait(TimeUnit.MINUTES.toMillis(1));
431 } catch (InterruptedException ie1) {
439 Map<Long, Network> timesForNextConnects = new TreeMap<>(missingNetworks.stream()
440 .collect(Collectors.toMap(connectionBackoff::getConnectionTime, Function.identity(), (network, ignore) -> network)));
442 Optional<Entry<Long, Network>> firstNetwork = Optional.fromNullable(timesForNextConnects.entrySet().stream().findFirst().orElse(null));
443 if (!firstNetwork.isPresent()) {
446 if (firstNetwork.get().getKey() > System.currentTimeMillis()) {
447 eventBus.post(new GenericMessage(String.format("Will connect to %2$s at %1$tH:%1$tM...", firstNetwork.get().getKey(), firstNetwork.get().getValue().name())));
448 synchronized (syncObject) {
450 syncObject.wait(firstNetwork.get().getKey() - System.currentTimeMillis());
451 } catch (InterruptedException ie1) {
458 if (firstNetwork.get().getKey() > System.currentTimeMillis()) {
463 connectNetwork(firstNetwork.get().getValue());
468 protected void triggerShutdown() {
469 synchronized (syncObject) {
470 syncObject.notifyAll();
479 * Starts a new connection for the given network if no such connection exists
483 * The network to connect to
485 private void connectNetwork(Network network) {
486 if (!networkConnections.containsKey(network)) {
487 /* select a random server. */
488 List<Server> servers = Lists.newArrayList(network.servers());
489 if (servers.isEmpty()) {
490 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
493 Server server = servers.get((int) (Math.random() * servers.size()));
494 eventBus.post(new GenericMessage(String.format("Connecting to %s on %s...", network.name(), server.hostname())));
495 Connection connection = connectionFactory.createConnection(server.hostname(),
496 server.unencryptedPorts().iterator().next());
497 connection.username(RandomNickname.get()).realName(RandomNickname.get());
498 networkConnections.put(network, connection);
504 * Removes the given connection and all its channels and bots.
507 * The connection to remove
509 private void removeConnection(Connection connection) {
510 logger.debug(String.format("Removing Connection %s...", connection));
511 Optional<Network> network = getNetwork(connection);
512 if (!network.isPresent()) {
513 logger.debug(String.format("Connection %s did not belong to any network.", connection));
516 logger.debug(String.format("Connection %s belongs to network %s.", connection, network.get()));
517 networkConnections.remove(network.get());
519 /* find all channels that need to be removed. */
520 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
521 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
522 Channel joinedChannel = channelIterator.next();
523 if (!joinedChannel.network().equals(network.get())) {
526 logger.debug(String.format("Channel %s will be removed.", joinedChannel));
527 channelIterator.remove();
531 /* now remove all bots for that network. */
532 Map<String, Bot> bots = networkBots.row(network.get());
533 int botCount = bots.size();
535 for (Bot bot : bots.values()) {
536 packCount += bot.packs().size();
539 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
547 * If a connection to a network has been established, the channels associated
548 * with this network are joined.
550 * @param connectionEstablished
551 * The connection established event
554 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
556 /* get network for connection. */
557 Optional<Network> network = getNetwork(connectionEstablished.connection());
560 if (!network.isPresent()) {
561 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
565 connectionBackoff.connectionSuccessful(network.get());
566 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
568 /* join all channels on this network. */
569 for (Channel channel : channels) {
570 if (channel.network().equals(network.get())) {
572 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
573 connectionEstablished.connection().joinChannel(channel.name());
574 } catch (IOException ioe1) {
575 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
582 * Remove all data stored for a network if the connection is closed.
584 * @param connectionClosed
585 * The connection closed event
588 public void connectionClosed(ConnectionClosed connectionClosed) {
589 connectionBackoff.connectionFailed(getNetwork(connectionClosed.connection()).get());
590 removeConnection(connectionClosed.connection());
591 synchronized (syncObject) {
592 syncObject.notifyAll();
594 eventBus.post(new GenericMessage(String.format("Connection closed by %s.", connectionClosed.connection().hostname())));
598 * Remove all data stored for a network if the connection fails.
600 * @param connectionFailed
601 * The connection failed event
604 public void connectionFailed(ConnectionFailed connectionFailed) {
605 connectionBackoff.connectionFailed(getNetwork(connectionFailed.connection()).get());
606 removeConnection(connectionFailed.connection());
607 synchronized (syncObject) {
608 syncObject.notifyAll();
610 eventBus.post(new GenericMessage(String.format("Could not connect to %s: %s.", connectionFailed.connection().hostname(), connectionFailed.cause())));
614 * Shows a message when a channel was joined by us.
616 * @param channelJoined
617 * The channel joined event
620 public void channelJoined(ChannelJoined channelJoined) {
621 if (channelJoined.connection().isSource(channelJoined.client())) {
622 Optional<Network> network = getNetwork(channelJoined.connection());
623 if (!network.isPresent()) {
627 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
628 if (!channel.isPresent()) {
629 /* it’s an extra channel. */
630 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
631 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
635 channelBanManager.unban(channel.get());
636 joinedChannels.add(channel.get());
637 channelsBeingJoined.remove(channel.get());
638 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
643 public void channelNotJoined(ChannelNotJoined channelNotJoined) {
644 Optional<Network> network = getNetwork(channelNotJoined.connection());
645 if (!network.isPresent()) {
649 Optional<Channel> channel = getChannel(network.get(), channelNotJoined.channel());
650 synchronized (syncObject) {
651 syncObject.notifyAll();
653 if (!channel.isPresent()) {
654 eventBus.post(new GenericMessage(format("Could not join %s but didn’t try to join, either.", channelNotJoined.channel())));
657 channelsBeingJoined.remove(channel.get());
660 /* remove all bots for this channel, we might have been kicked. */
661 Collection<Bot> botsToRemove = networkBots.row(network.get())
663 .filter(bot -> bot.channel()
664 .equalsIgnoreCase(channel.get().name()))
665 .collect(Collectors.toSet());
666 botsToRemove.stream()
667 .forEach(bot -> networkBots.row(network.get())
668 .remove(bot.name()));
670 channelBanManager.ban(channel.get());
671 if (channelNotJoined.reason() == registeredNicknamesOnly) {
672 eventBus.post(new GenericMessage(
673 format("%s requires nickname registration, suspending join for a day.",
675 } else if (channelNotJoined.reason() == inviteOnly) {
676 eventBus.post(new GenericMessage(
677 format("%s is invite-only, suspending join for a day.",
679 } else if (channelNotJoined.reason() == banned) {
680 eventBus.post(new GenericMessage(
681 format("Banned from %s, suspending join for a day.",
684 eventBus.post(new GenericMessage(
685 format("Could not join %s: %s", channelNotJoined.channel(),
686 channelNotJoined.reason())));
691 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
694 * The channel left event
697 public void channelLeft(ChannelLeft channelLeft) {
698 Optional<Network> network = getNetwork(channelLeft.connection());
699 if (!network.isPresent()) {
703 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
705 /* maybe it was us? */
706 if (channelLeft.connection().isSource(channelLeft.client())) {
707 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
708 if (!channel.isPresent()) {
709 /* maybe it was an extra channel? */
710 channel = getExtraChannel(network.get(), channelLeft.channel());
711 if (!channel.isPresent()) {
712 /* okay, whatever. */
716 extraChannels.remove(channel);
718 channels.remove(channel.get());
720 synchronized (syncObject) {
721 syncObject.notifyAll();
724 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
730 networkBots.remove(network.get(), channelLeft.client().nick().get());
734 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
735 Optional<Network> network = getNetwork(kickedFromChannel.connection());
736 if (!network.isPresent()) {
740 /* have we been kicked? */
741 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
742 Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
743 if (!channel.isPresent()) {
744 /* maybe it was an extra channel? */
745 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
746 if (!channel.isPresent()) {
747 /* okay, whatever. */
751 extraChannels.remove(channel.get());
753 joinedChannels.remove(channel.get());
755 synchronized (syncObject) {
756 syncObject.notifyAll();
758 eventBus.post(new GenericMessage(format(
759 "Kicked from %s by %s: %s",
760 kickedFromChannel.channel(),
761 kickedFromChannel.kicker(),
762 kickedFromChannel.reason().orElse("<unknown>")
767 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
768 return connection.nickname().equalsIgnoreCase(nickname);
772 * Removes a client (which may be a bot) from the table of known bots.
775 * The client quit event
778 public void clientQuit(ClientQuit clientQuit) {
779 Optional<Network> network = getNetwork(clientQuit.connection());
780 if (!network.isPresent()) {
784 networkBots.remove(network.get(), clientQuit.client().nick().get());
788 * If the nickname of a bit changes, remove it from the old name and store it
789 * under the new name.
791 * @param nicknameChanged
792 * The nickname changed event
795 public void nicknameChanged(NicknameChanged nicknameChanged) {
796 Optional<Network> network = getNetwork(nicknameChanged.connection());
797 if (!network.isPresent()) {
801 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
806 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
810 * If a message on a channel is received, it is parsed for pack information
811 * with is then added to a bot.
813 * @param channelMessageReceived
814 * The channel message received event
817 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
818 String message = getDefaultInstance().clean(channelMessageReceived.message());
819 if (!message.startsWith("#")) {
820 /* most probably not a pack announcement. */
824 Optional<Network> network = getNetwork(channelMessageReceived.connection());
825 if (!network.isPresent()) {
826 /* message for unknown connection? */
830 /* parse pack information. */
831 Optional<Pack> pack = parsePack(message);
832 if (!pack.isPresent()) {
837 synchronized (networkBots) {
838 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
839 bot = new Bot(network.get(), channelMessageReceived.channel(),
840 channelMessageReceived.source().nick().get());
841 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
842 eventBus.post(new BotAdded(bot));
844 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
849 bot.addPack(pack.get());
850 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
854 * Forward all private messages to every console.
856 * @param privateMessageReceived
857 * The private message recevied event
860 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
861 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
865 * Sends a message to all console when a notice was received.
867 * @param privateNoticeReceived
868 * The notice received event
871 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
872 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
873 if (!network.isPresent()) {
877 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.source(), network.get(), privateNoticeReceived.text())));
881 * Starts a DCC download.
883 * @param dccSendReceived
887 public void dccSendReceived(final DccSendReceived dccSendReceived) {
888 final Optional<Network> network = getNetwork(dccSendReceived.connection());
889 if (!network.isPresent()) {
893 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
894 if (packDownloads.isEmpty()) {
895 /* unknown download, ignore. */
899 /* check if it’s already downloading. */
900 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
901 if (!runningDownloads.isEmpty()) {
902 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
906 /* locate the correct download. */
907 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
910 public boolean apply(Download download) {
911 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
915 /* we did not request this download. */
916 if (requestedDownload.isEmpty()) {
920 Download download = requestedDownload.iterator().next();
922 /* check if the file already exists. */
923 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
924 if (outputFile.exists()) {
925 long existingFileSize = outputFile.length();
927 /* file already complete? */
928 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
929 /* file is apparently already complete. just move it. */
930 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
931 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
933 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
936 /* remove download. */
937 downloads.removeAll(download.pack().name());
941 /* file not complete yet, DCC resume it. */
943 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
944 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
945 } catch (IOException ioe1) {
946 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
952 /* file does not exist, start the download. */
954 OutputStream fileOutputStream = new FileOutputStream(outputFile);
955 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
956 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
957 dccReceivers.add(dccReceiver);
959 eventBus.post(new DownloadStarted(download));
960 } catch (FileNotFoundException fnfe1) {
961 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
966 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
967 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
968 if (!network.isPresent()) {
972 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
973 if (packDownloads.isEmpty()) {
974 /* unknown download, ignore. */
978 /* check if it’s already downloading. */
979 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
980 if (!runningDownloads.isEmpty()) {
981 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
985 /* locate the correct download. */
986 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
989 public boolean apply(Download download) {
990 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
994 /* we did not request this download. */
995 if (requestedDownload.isEmpty()) {
999 Download download = requestedDownload.iterator().next();
1002 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
1003 if (outputFile.length() != dccAcceptReceived.position()) {
1004 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
1005 logger.warn(String.format("Download %s from %s: have %d bytes but wants to resume from %d!", dccAcceptReceived.filename(), dccAcceptReceived.source(), outputFile.length(), dccAcceptReceived.position()));
1007 downloads.removeAll(download.pack().name());
1010 OutputStream outputStream = new FileOutputStream(outputFile, true);
1011 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
1012 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
1013 dccReceivers.add(dccReceiver);
1014 dccReceiver.start();
1015 eventBus.post(new DownloadStarted(download));
1016 } catch (FileNotFoundException fnfe1) {
1021 * Closes the output stream of the download and moves the file to the final
1024 * @param dccDownloadFinished
1025 * The DCC download finished event
1028 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
1030 /* locate the correct download. */
1031 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
1032 if (requestedDownload.isEmpty()) {
1033 /* this seems wrong. */
1034 logger.warn("Download finished but could not be located.");
1037 Download download = requestedDownload.iterator().next();
1040 download.outputStream().close();
1041 File file = new File(download.filename());
1042 file.renameTo(new File(finalDirectory, download.pack().name()));
1043 eventBus.post(new DownloadFinished(download));
1044 dccReceivers.remove(dccDownloadFinished.dccReceiver());
1045 downloads.removeAll(download.pack().name());
1046 } catch (IOException ioe1) {
1047 /* TODO - handle all the errors. */
1048 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
1053 * Closes the output stream and notifies all listeners of the failure.
1055 * @param dccDownloadFailed
1056 * The DCC download failed event
1059 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
1061 /* locate the correct download. */
1062 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
1063 if (requestedDownload.isEmpty()) {
1064 /* this seems wrong. */
1065 logger.warn("Download finished but could not be located.");
1068 Download download = requestedDownload.iterator().next();
1071 Closeables.close(download.outputStream(), true);
1072 eventBus.post(new DownloadFailed(download));
1073 dccReceivers.remove(dccDownloadFailed.dccReceiver());
1074 downloads.removeAll(download.pack().name());
1075 } catch (IOException ioe1) {
1076 /* swallow silently. */
1081 public void replyReceived(ReplyReceived replyReceived) {
1082 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
1090 * Returns the download of the given pack from the given bot.
1093 * The pack being downloaded
1095 * The bot the pack is being downloaded from
1096 * @return The download, or {@link Optional#absent()} if the download could not
1099 private Optional<Download> getDownload(Pack pack, Bot bot) {
1100 if (!downloads.containsKey(pack.name())) {
1101 return Optional.absent();
1103 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
1104 if (download.bot().equals(bot)) {
1105 return Optional.of(download);
1108 return Optional.absent();
1112 * Searches all current connections for the given connection, returning the
1113 * associated network.
1116 * The connection to get the network for
1117 * @return The network belonging to the connection, or {@link
1118 * Optional#absent()}
1120 private Optional<Network> getNetwork(Connection connection) {
1121 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
1122 if (networkConnectionEntry.getValue().equals(connection)) {
1123 return Optional.of(networkConnectionEntry.getKey());
1126 return Optional.absent();
1130 * Returns the configured channel for the given network and name.
1133 * The network the channel is located on
1134 * @param channelName
1135 * The name of the channel
1136 * @return The configured channel, or {@link Optional#absent()} if no
1137 * configured channel matching the given network and name was found
1139 public Optional<Channel> getChannel(Network network, String channelName) {
1140 for (Channel channel : channels) {
1141 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1142 return Optional.of(channel);
1145 return Optional.absent();
1149 * Returns the extra channel for the given network and name.
1152 * The network the channel is located on
1153 * @param channelName
1154 * The name of the channel
1155 * @return The extra channel, or {@link Optional#absent()} if no extra channel
1156 * matching the given network and name was found
1158 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1159 for (Channel channel : extraChannels) {
1160 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1161 return Optional.of(channel);
1164 return Optional.absent();
1168 * Parses {@link Pack} information from the given message.
1171 * The message to parse pack information from
1172 * @return The parsed pack, or {@link Optional#absent()} if the message could
1173 * not be parsed into a pack
1175 private Optional<Pack> parsePack(String message) {
1176 int squareOpen = message.indexOf('[');
1177 int squareClose = message.indexOf(']', squareOpen);
1178 if ((squareOpen == -1) && (squareClose == -1)) {
1179 return Optional.absent();
1181 String packSize = message.substring(squareOpen + 1, squareClose);
1182 String packName = message.substring(message.lastIndexOf(' ') + 1);
1183 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1184 return Optional.of(new Pack(packIndex, packSize, packName));