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.Channel.TO_NETWORK;
26 import static net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
29 import java.io.FileNotFoundException;
30 import java.io.FileOutputStream;
31 import java.io.IOException;
32 import java.io.OutputStream;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashSet;
36 import java.util.Iterator;
37 import java.util.List;
39 import java.util.Map.Entry;
41 import java.util.TreeMap;
42 import java.util.concurrent.TimeUnit;
43 import java.util.function.Function;
44 import java.util.stream.Collectors;
46 import net.pterodactylus.irc.Connection;
47 import net.pterodactylus.irc.ConnectionFactory;
48 import net.pterodactylus.irc.DccReceiver;
49 import net.pterodactylus.irc.DefaultConnection;
50 import net.pterodactylus.irc.event.ChannelJoined;
51 import net.pterodactylus.irc.event.ChannelLeft;
52 import net.pterodactylus.irc.event.ChannelMessageReceived;
53 import net.pterodactylus.irc.event.ChannelNotJoined;
54 import net.pterodactylus.irc.event.ClientQuit;
55 import net.pterodactylus.irc.event.ConnectionClosed;
56 import net.pterodactylus.irc.event.ConnectionEstablished;
57 import net.pterodactylus.irc.event.ConnectionFailed;
58 import net.pterodactylus.irc.event.DccAcceptReceived;
59 import net.pterodactylus.irc.event.DccDownloadFailed;
60 import net.pterodactylus.irc.event.DccDownloadFinished;
61 import net.pterodactylus.irc.event.DccSendReceived;
62 import net.pterodactylus.irc.event.KickedFromChannel;
63 import net.pterodactylus.irc.event.NicknameChanged;
64 import net.pterodactylus.irc.event.PrivateMessageReceived;
65 import net.pterodactylus.irc.event.PrivateNoticeReceived;
66 import net.pterodactylus.irc.event.ReplyReceived;
67 import net.pterodactylus.irc.util.RandomNickname;
68 import net.pterodactylus.xdcc.core.event.BotAdded;
69 import net.pterodactylus.xdcc.core.event.CoreStarted;
70 import net.pterodactylus.xdcc.core.event.DownloadFailed;
71 import net.pterodactylus.xdcc.core.event.DownloadFinished;
72 import net.pterodactylus.xdcc.core.event.DownloadStarted;
73 import net.pterodactylus.xdcc.core.event.GenericError;
74 import net.pterodactylus.xdcc.core.event.GenericMessage;
75 import net.pterodactylus.xdcc.core.event.MessageReceived;
76 import net.pterodactylus.xdcc.data.Bot;
77 import net.pterodactylus.xdcc.data.Channel;
78 import net.pterodactylus.xdcc.data.ConnectedNetwork;
79 import net.pterodactylus.xdcc.data.Download;
80 import net.pterodactylus.xdcc.data.Network;
81 import net.pterodactylus.xdcc.data.Pack;
82 import net.pterodactylus.xdcc.data.Server;
84 import com.google.common.base.Optional;
85 import com.google.common.base.Predicate;
86 import com.google.common.collect.FluentIterable;
87 import com.google.common.collect.HashBasedTable;
88 import com.google.common.collect.HashMultimap;
89 import com.google.common.collect.ImmutableList;
90 import com.google.common.collect.ImmutableSet;
91 import com.google.common.collect.Lists;
92 import com.google.common.collect.Maps;
93 import com.google.common.collect.Multimap;
94 import com.google.common.collect.Sets;
95 import com.google.common.collect.Table;
96 import com.google.common.eventbus.EventBus;
97 import com.google.common.eventbus.Subscribe;
98 import com.google.common.io.Closeables;
99 import com.google.common.util.concurrent.AbstractExecutionThreadService;
100 import com.google.inject.Inject;
101 import org.apache.log4j.Logger;
104 * The core of XDCC Downloader.
106 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
108 public class Core extends AbstractExecutionThreadService {
111 private static final Logger logger = Logger.getLogger(Core.class.getName());
113 private final Object syncObject = new Object();
114 /** The event bus. */
115 private final EventBus eventBus;
116 private final ConnectionFactory connectionFactory;
117 private final ChannelBanManager channelBanManager =
118 new ChannelBanManager();
119 private final ConnectionBackoff connectionBackoff = new ConnectionBackoff();
121 /** The temporary directory to download files to. */
122 private final String temporaryDirectory;
124 /** The directory to move finished downloads to. */
125 private final String finalDirectory;
127 /** The channels that should be monitored. */
128 private final Collection<Channel> channels = Sets.newHashSet();
130 /** The channels that are currentlymonitored. */
131 private final Collection<Channel> joinedChannels = Sets.newHashSet();
132 private final Set<Channel> channelsBeingJoined = new HashSet<>();
134 /** The channels that are joined but not configured. */
135 private final Collection<Channel> extraChannels = Sets.newHashSet();
137 /** The current network connections. */
138 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
140 /** The currently known bots. */
141 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
143 /** The current downloads. */
144 private final Multimap<String, Download> downloads = HashMultimap.create();
146 /** The current DCC receivers. */
147 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
150 * Creates a new core.
154 * @param temporaryDirectory
155 * The directory to download files to
156 * @param finalDirectory
157 * The directory to move finished files to
160 public Core(EventBus eventBus, ConnectionFactory connectionFactory, String temporaryDirectory, String finalDirectory) {
161 this.eventBus = eventBus;
162 this.connectionFactory = connectionFactory;
163 this.temporaryDirectory = temporaryDirectory;
164 this.finalDirectory = finalDirectory;
172 * Returns all currently known connections.
174 * @return All currently known connections
176 public Collection<Connection> connections() {
177 return networkConnections.values();
181 * Returns all defined networks.
183 * @return All defined networks
185 public Collection<Network> networks() {
186 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
190 * Returns all connected networks.
192 * @return All connected networks
194 public Collection<ConnectedNetwork> connectedNetworks() {
195 return networkConnections.entrySet().stream().map((entry) -> {
196 Network network = entry.getKey();
197 Collection<Bot> bots = networkBots.row(network).values();
198 int packCount = bots.stream().mapToInt((bot) -> bot.packs().size()).reduce((a, b) -> a + b).orElse(0);
199 return new ConnectedNetwork(network, entry.getValue().hostname(),
200 entry.getValue().port(), entry.getValue().nickname(),
202 .filter((channel) -> channel.network()
205 .collect(Collectors.<String>toList()),
206 extraChannels.stream()
207 .filter((channel) -> channel.network()
210 .collect(Collectors.<String>toList()),
211 bots.size(), packCount);
212 }).collect(Collectors.<ConnectedNetwork>toList());
216 * Returns all configured channels. Due to various circumstances, configured
217 * channels might not actually be joined.
219 * @return All configured channels
221 public Collection<Channel> channels() {
222 return ImmutableSet.copyOf(channels);
226 * Returns all currently joined channels.
228 * @return All currently joined channels
230 public Collection<Channel> joinedChannels() {
231 return ImmutableSet.copyOf(joinedChannels);
235 * Returns all currently joined channels that are not configured.
237 * @return All currently joined but not configured channels
239 public Collection<Channel> extraChannels() {
240 return ImmutableSet.copyOf(extraChannels);
244 * Returns all currently known bots.
246 * @return All currently known bots
248 public Collection<Bot> bots() {
249 return networkBots.values();
253 * Returns all currently running downloads.
255 * @return All currently running downloads
257 public Collection<Download> downloads() {
258 return downloads.values();
266 * Adds a channel to monitor.
269 * The channel to monitor
271 public void addChannel(Channel channel) {
272 channels.add(channel);
276 * Fetches the given pack from the given bot.
279 * The bot to fetch the pack from
283 public void fetch(Bot bot, Pack pack) {
284 Connection connection = networkConnections.get(bot.network());
285 if (connection == null) {
289 /* check if we are already downloading the file? */
290 if (downloads.containsKey(pack.name())) {
291 Collection<Download> packDownloads = downloads.get(pack.name());
292 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
293 if (!runningDownloads.isEmpty()) {
294 Download download = runningDownloads.iterator().next();
295 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
298 StringBuilder bots = new StringBuilder();
299 for (Download download : packDownloads) {
300 if (bots.length() > 0) {
303 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
305 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
308 Download download = new Download(bot, pack);
309 downloads.put(pack.name(), download);
312 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
313 } catch (IOException ioe1) {
314 logger.warn("Could not send message to bot!", ioe1);
319 * Cancels the download of the given pack from the given bot.
322 * The bot the pack is being downloaded from
324 * The pack being downloaded
326 public void cancelDownload(Bot bot, Pack pack) {
327 Optional<Download> download = getDownload(pack, bot);
328 if (!download.isPresent()) {
332 /* get connection. */
333 Connection connection = networkConnections.get(bot.network());
334 if (connection == null) {
335 /* request for unknown network? */
339 /* stop the DCC receiver. */
340 if (download.get().dccReceiver() != null) {
341 download.get().dccReceiver().stop();
343 /* remove download if it hasn’t started yet. */
344 downloads.remove(pack.name(), download.get());
347 /* remove the request from the bot, too. */
349 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
350 } catch (IOException ioe1) {
351 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
356 * Closes the given connection.
359 * The connection to close
361 public void closeConnection(Connection connection) {
364 } catch (IOException ioe1) {
370 // ABSTRACTIDLESERVICE METHODS
374 protected void startUp() {
375 for (Channel channel : channels) {
376 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
377 connectNetwork(channel.network());
380 /* notify listeners. */
381 eventBus.post(new CoreStarted(this));
385 protected void run() throws Exception {
386 while (isRunning()) {
388 Set<Channel> missingChannels = new HashSet<>();
389 for (Channel channel : channels) {
390 if (joinedChannels.contains(channel) || channelsBeingJoined.contains(channel)) {
393 if (channelBanManager.isBanned(channel)) {
396 if (!networkConnections.containsKey(channel.network()) || networkConnections.get(channel.network()).established()) {
397 missingChannels.add(channel);
400 Set<Network> missingNetworks = missingChannels.stream()
401 .map(Channel::network)
403 .filter((network) -> !networkConnections.containsKey(network))
404 .collect(Collectors.toSet());
406 if (missingNetworks.isEmpty()) {
407 if (!missingChannels.isEmpty()) {
408 for (Channel missingChannel : missingChannels) {
409 Network network = missingChannel.network();
410 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", missingChannel.name(), network)));
412 channelsBeingJoined.add(missingChannel);
413 networkConnections.get(network).joinChannel(missingChannel.name());
414 } catch (IOException ioe1) {
415 logger.warn(String.format("Could not join %s on %s!", missingChannel.name(), network.name()), ioe1);
419 synchronized (syncObject) {
421 syncObject.wait(TimeUnit.MINUTES.toMillis(1));
422 } catch (InterruptedException ie1) {
430 Map<Long, Network> timesForNextConnects = new TreeMap<>(missingNetworks.stream()
431 .collect(Collectors.toMap(connectionBackoff::getConnectionTime, Function.identity(), (network, ignore) -> network)));
433 Optional<Entry<Long, Network>> firstNetwork = Optional.fromNullable(timesForNextConnects.entrySet().stream().findFirst().orElse(null));
434 if (!firstNetwork.isPresent()) {
437 if (firstNetwork.get().getKey() > System.currentTimeMillis()) {
438 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())));
439 synchronized (syncObject) {
441 syncObject.wait(firstNetwork.get().getKey() - System.currentTimeMillis());
442 } catch (InterruptedException ie1) {
449 if (firstNetwork.get().getKey() > System.currentTimeMillis()) {
454 connectNetwork(firstNetwork.get().getValue());
459 protected void triggerShutdown() {
460 synchronized (syncObject) {
461 syncObject.notifyAll();
470 * Starts a new connection for the given network if no such connection exists
474 * The network to connect to
476 private void connectNetwork(Network network) {
477 if (!networkConnections.containsKey(network)) {
478 /* select a random server. */
479 List<Server> servers = Lists.newArrayList(network.servers());
480 if (servers.isEmpty()) {
481 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
484 Server server = servers.get((int) (Math.random() * servers.size()));
485 eventBus.post(new GenericMessage(String.format("Connecting to %s on %s...", network.name(), server.hostname())));
486 Connection connection = connectionFactory.createConnection(server.hostname(),
487 server.unencryptedPorts().iterator().next());
488 connection.username(RandomNickname.get()).realName(RandomNickname.get());
489 networkConnections.put(network, connection);
495 * Removes the given connection and all its channels and bots.
498 * The connection to remove
500 private void removeConnection(Connection connection) {
501 Optional<Network> network = getNetwork(connection);
502 if (!network.isPresent()) {
505 networkConnections.remove(network.get());
506 if (!connection.established()) {
510 /* find all channels that need to be removed. */
511 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
512 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
513 Channel joinedChannel = channelIterator.next();
514 if (!joinedChannel.network().equals(network.get())) {
518 channelIterator.remove();
522 /* now remove all bots for that network. */
523 Map<String, Bot> bots = networkBots.row(network.get());
524 int botCount = bots.size();
526 for (Bot bot : bots.values()) {
527 packCount += bot.packs().size();
530 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
538 * If a connection to a network has been established, the channels associated
539 * with this network are joined.
541 * @param connectionEstablished
542 * The connection established event
545 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
547 /* get network for connection. */
548 Optional<Network> network = getNetwork(connectionEstablished.connection());
551 if (!network.isPresent()) {
552 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
556 connectionBackoff.connectionSuccessful(network.get());
557 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
559 /* join all channels on this network. */
560 for (Channel channel : channels) {
561 if (channel.network().equals(network.get())) {
563 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
564 connectionEstablished.connection().joinChannel(channel.name());
565 } catch (IOException ioe1) {
566 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
573 * Remove all data stored for a network if the connection is closed.
575 * @param connectionClosed
576 * The connection closed event
579 public void connectionClosed(ConnectionClosed connectionClosed) {
580 connectionBackoff.connectionFailed(getNetwork(connectionClosed.connection()).get());
581 removeConnection(connectionClosed.connection());
582 synchronized (syncObject) {
583 syncObject.notifyAll();
585 eventBus.post(new GenericMessage(String.format("Connection closed by %s.", connectionClosed.connection().hostname())));
589 * Remove all data stored for a network if the connection fails.
591 * @param connectionFailed
592 * The connection failed event
595 public void connectionFailed(ConnectionFailed connectionFailed) {
596 connectionBackoff.connectionFailed(getNetwork(connectionFailed.connection()).get());
597 removeConnection(connectionFailed.connection());
598 synchronized (syncObject) {
599 syncObject.notifyAll();
601 eventBus.post(new GenericMessage(String.format("Could not connect to %s: %s.", connectionFailed.connection().hostname(), connectionFailed.cause())));
605 * Shows a message when a channel was joined by us.
607 * @param channelJoined
608 * The channel joined event
611 public void channelJoined(ChannelJoined channelJoined) {
612 if (channelJoined.connection().isSource(channelJoined.client())) {
613 Optional<Network> network = getNetwork(channelJoined.connection());
614 if (!network.isPresent()) {
618 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
619 if (!channel.isPresent()) {
620 /* it’s an extra channel. */
621 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
622 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
626 channelBanManager.unban(channel.get());
627 joinedChannels.add(channel.get());
628 channelsBeingJoined.remove(channel.get());
629 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
634 public void channelNotJoined(ChannelNotJoined channelNotJoined) {
635 Optional<Network> network = getNetwork(channelNotJoined.connection());
636 if (!network.isPresent()) {
640 Optional<Channel> channel = getChannel(network.get(), channelNotJoined.channel());
641 synchronized (syncObject) {
642 syncObject.notifyAll();
644 if (!channel.isPresent()) {
645 eventBus.post(new GenericMessage(format("Could not join %s but didn’t try to join, either.", channelNotJoined.channel())));
648 channelsBeingJoined.remove(channel.get());
651 /* remove all bots for this channel, we might have been kicked. */
652 Collection<Bot> botsToRemove = networkBots.row(network.get())
654 .filter(bot -> bot.channel()
655 .equalsIgnoreCase(channel.get().name()))
656 .collect(Collectors.toSet());
657 botsToRemove.stream()
658 .forEach(bot -> networkBots.row(network.get())
659 .remove(bot.name()));
661 if (channelNotJoined.reason() == registeredNicknamesOnly) {
662 channels.remove(channel.get());
663 eventBus.post(new GenericMessage(
664 format("Not trying to join %s anymore.", channel.get())));
667 if (channelNotJoined.reason() == inviteOnly) {
668 channelBanManager.ban(channel.get());
669 eventBus.post(new GenericMessage(
670 format("%s is invite-only, suspending join for a day.",
674 if (channelNotJoined.reason() == banned) {
675 channelBanManager.ban(channel.get());
676 eventBus.post(new GenericMessage(
677 format("Banned from %s, suspending join for a day.",
682 eventBus.post(new GenericMessage(
683 format("Could not join %s: %s", channelNotJoined.channel(),
684 channelNotJoined.reason())));
688 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
691 * The channel left event
694 public void channelLeft(ChannelLeft channelLeft) {
695 Optional<Network> network = getNetwork(channelLeft.connection());
696 if (!network.isPresent()) {
700 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
702 /* maybe it was us? */
703 if (channelLeft.connection().isSource(channelLeft.client())) {
704 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
705 if (!channel.isPresent()) {
706 /* maybe it was an extra channel? */
707 channel = getExtraChannel(network.get(), channelLeft.channel());
708 if (!channel.isPresent()) {
709 /* okay, whatever. */
713 extraChannels.remove(channel);
715 channels.remove(channel.get());
717 synchronized (syncObject) {
718 syncObject.notifyAll();
721 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
727 networkBots.remove(network.get(), channelLeft.client().nick().get());
731 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
732 Optional<Network> network = getNetwork(kickedFromChannel.connection());
733 if (!network.isPresent()) {
737 /* have we been kicked? */
738 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
739 Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
740 if (!channel.isPresent()) {
741 /* maybe it was an extra channel? */
742 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
743 if (!channel.isPresent()) {
744 /* okay, whatever. */
748 extraChannels.remove(channel.get());
750 joinedChannels.remove(channel.get());
752 synchronized (syncObject) {
753 syncObject.notifyAll();
755 eventBus.post(new GenericMessage(format(
756 "Kicked from %s by %s: %s",
757 kickedFromChannel.channel(),
758 kickedFromChannel.kicker(),
759 kickedFromChannel.reason().or("<unknown>")
764 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
765 return connection.nickname().equalsIgnoreCase(nickname);
769 * Removes a client (which may be a bot) from the table of known bots.
772 * The client quit event
775 public void clientQuit(ClientQuit clientQuit) {
776 Optional<Network> network = getNetwork(clientQuit.connection());
777 if (!network.isPresent()) {
781 networkBots.remove(network.get(), clientQuit.client().nick().get());
785 * If the nickname of a bit changes, remove it from the old name and store it
786 * under the new name.
788 * @param nicknameChanged
789 * The nickname changed event
792 public void nicknameChanged(NicknameChanged nicknameChanged) {
793 Optional<Network> network = getNetwork(nicknameChanged.connection());
794 if (!network.isPresent()) {
798 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
803 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
807 * If a message on a channel is received, it is parsed for pack information
808 * with is then added to a bot.
810 * @param channelMessageReceived
811 * The channel message received event
814 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
815 String message = getDefaultInstance().clean(channelMessageReceived.message());
816 if (!message.startsWith("#")) {
817 /* most probably not a pack announcement. */
821 Optional<Network> network = getNetwork(channelMessageReceived.connection());
822 if (!network.isPresent()) {
823 /* message for unknown connection? */
827 /* parse pack information. */
828 Optional<Pack> pack = parsePack(message);
829 if (!pack.isPresent()) {
834 synchronized (networkBots) {
835 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
836 bot = new Bot(network.get(), channelMessageReceived.channel(),
837 channelMessageReceived.source().nick().get());
838 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
839 eventBus.post(new BotAdded(bot));
841 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
846 bot.addPack(pack.get());
847 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
851 * Forward all private messages to every console.
853 * @param privateMessageReceived
854 * The private message recevied event
857 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
858 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
862 * Sends a message to all console when a notice was received.
864 * @param privateNoticeReceived
865 * The notice received event
868 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
869 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
870 if (!network.isPresent()) {
874 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.source(), network.get(), privateNoticeReceived.text())));
878 * Starts a DCC download.
880 * @param dccSendReceived
884 public void dccSendReceived(final DccSendReceived dccSendReceived) {
885 final Optional<Network> network = getNetwork(dccSendReceived.connection());
886 if (!network.isPresent()) {
890 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
891 if (packDownloads.isEmpty()) {
892 /* unknown download, ignore. */
896 /* check if it’s already downloading. */
897 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
898 if (!runningDownloads.isEmpty()) {
899 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
903 /* locate the correct download. */
904 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
907 public boolean apply(Download download) {
908 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
912 /* we did not request this download. */
913 if (requestedDownload.isEmpty()) {
917 Download download = requestedDownload.iterator().next();
919 /* check if the file already exists. */
920 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
921 if (outputFile.exists()) {
922 long existingFileSize = outputFile.length();
924 /* file already complete? */
925 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
926 /* file is apparently already complete. just move it. */
927 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
928 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
930 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
933 /* remove download. */
934 downloads.removeAll(download.pack().name());
938 /* file not complete yet, DCC resume it. */
940 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
941 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
942 } catch (IOException ioe1) {
943 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
949 /* file does not exist, start the download. */
951 OutputStream fileOutputStream = new FileOutputStream(outputFile);
952 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
953 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
954 dccReceivers.add(dccReceiver);
956 eventBus.post(new DownloadStarted(download));
957 } catch (FileNotFoundException fnfe1) {
958 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
963 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
964 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
965 if (!network.isPresent()) {
969 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
970 if (packDownloads.isEmpty()) {
971 /* unknown download, ignore. */
975 /* check if it’s already downloading. */
976 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
977 if (!runningDownloads.isEmpty()) {
978 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
982 /* locate the correct download. */
983 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
986 public boolean apply(Download download) {
987 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
991 /* we did not request this download. */
992 if (requestedDownload.isEmpty()) {
996 Download download = requestedDownload.iterator().next();
999 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
1000 if (outputFile.length() != dccAcceptReceived.position()) {
1001 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
1002 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()));
1004 downloads.removeAll(download.pack().name());
1007 OutputStream outputStream = new FileOutputStream(outputFile, true);
1008 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
1009 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
1010 dccReceivers.add(dccReceiver);
1011 dccReceiver.start();
1012 eventBus.post(new DownloadStarted(download));
1013 } catch (FileNotFoundException fnfe1) {
1018 * Closes the output stream of the download and moves the file to the final
1021 * @param dccDownloadFinished
1022 * The DCC download finished event
1025 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
1027 /* locate the correct download. */
1028 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
1029 if (requestedDownload.isEmpty()) {
1030 /* this seems wrong. */
1031 logger.warn("Download finished but could not be located.");
1034 Download download = requestedDownload.iterator().next();
1037 download.outputStream().close();
1038 File file = new File(download.filename());
1039 file.renameTo(new File(finalDirectory, download.pack().name()));
1040 eventBus.post(new DownloadFinished(download));
1041 dccReceivers.remove(dccDownloadFinished.dccReceiver());
1042 downloads.removeAll(download.pack().name());
1043 } catch (IOException ioe1) {
1044 /* TODO - handle all the errors. */
1045 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
1050 * Closes the output stream and notifies all listeners of the failure.
1052 * @param dccDownloadFailed
1053 * The DCC download failed event
1056 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
1058 /* locate the correct download. */
1059 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
1060 if (requestedDownload.isEmpty()) {
1061 /* this seems wrong. */
1062 logger.warn("Download finished but could not be located.");
1065 Download download = requestedDownload.iterator().next();
1068 Closeables.close(download.outputStream(), true);
1069 eventBus.post(new DownloadFailed(download));
1070 dccReceivers.remove(dccDownloadFailed.dccReceiver());
1071 downloads.removeAll(download.pack().name());
1072 } catch (IOException ioe1) {
1073 /* swallow silently. */
1078 public void replyReceived(ReplyReceived replyReceived) {
1079 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
1087 * Returns the download of the given pack from the given bot.
1090 * The pack being downloaded
1092 * The bot the pack is being downloaded from
1093 * @return The download, or {@link Optional#absent()} if the download could not
1096 private Optional<Download> getDownload(Pack pack, Bot bot) {
1097 if (!downloads.containsKey(pack.name())) {
1098 return Optional.absent();
1100 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
1101 if (download.bot().equals(bot)) {
1102 return Optional.of(download);
1105 return Optional.absent();
1109 * Searches all current connections for the given connection, returning the
1110 * associated network.
1113 * The connection to get the network for
1114 * @return The network belonging to the connection, or {@link
1115 * Optional#absent()}
1117 private Optional<Network> getNetwork(Connection connection) {
1118 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
1119 if (networkConnectionEntry.getValue().equals(connection)) {
1120 return Optional.of(networkConnectionEntry.getKey());
1123 return Optional.absent();
1127 * Returns the configured channel for the given network and name.
1130 * The network the channel is located on
1131 * @param channelName
1132 * The name of the channel
1133 * @return The configured channel, or {@link Optional#absent()} if no
1134 * configured channel matching the given network and name was found
1136 public Optional<Channel> getChannel(Network network, String channelName) {
1137 for (Channel channel : channels) {
1138 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1139 return Optional.of(channel);
1142 return Optional.absent();
1146 * Returns the extra channel for the given network and name.
1149 * The network the channel is located on
1150 * @param channelName
1151 * The name of the channel
1152 * @return The extra channel, or {@link Optional#absent()} if no extra channel
1153 * matching the given network and name was found
1155 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1156 for (Channel channel : extraChannels) {
1157 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1158 return Optional.of(channel);
1161 return Optional.absent();
1165 * Parses {@link Pack} information from the given message.
1168 * The message to parse pack information from
1169 * @return The parsed pack, or {@link Optional#absent()} if the message could
1170 * not be parsed into a pack
1172 private Optional<Pack> parsePack(String message) {
1173 int squareOpen = message.indexOf('[');
1174 int squareClose = message.indexOf(']', squareOpen);
1175 if ((squareOpen == -1) && (squareClose == -1)) {
1176 return Optional.absent();
1178 String packSize = message.substring(squareOpen + 1, squareClose);
1179 String packName = message.substring(message.lastIndexOf(' ') + 1);
1180 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1181 return Optional.of(new Pack(packIndex, packSize, packName));