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.registeredNicknamesOnly;
23 import static net.pterodactylus.irc.util.MessageCleaner.getDefaultInstance;
24 import static net.pterodactylus.xdcc.data.Channel.TO_NETWORK;
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.util.Collection;
33 import java.util.Collections;
34 import java.util.Iterator;
35 import java.util.List;
37 import java.util.Map.Entry;
38 import java.util.concurrent.TimeUnit;
39 import java.util.stream.Collectors;
41 import net.pterodactylus.irc.Connection;
42 import net.pterodactylus.irc.ConnectionFactory;
43 import net.pterodactylus.irc.DccReceiver;
44 import net.pterodactylus.irc.DefaultConnection;
45 import net.pterodactylus.irc.event.ChannelJoined;
46 import net.pterodactylus.irc.event.ChannelLeft;
47 import net.pterodactylus.irc.event.ChannelMessageReceived;
48 import net.pterodactylus.irc.event.ChannelNotJoined;
49 import net.pterodactylus.irc.event.ClientQuit;
50 import net.pterodactylus.irc.event.ConnectionClosed;
51 import net.pterodactylus.irc.event.ConnectionEstablished;
52 import net.pterodactylus.irc.event.ConnectionFailed;
53 import net.pterodactylus.irc.event.DccAcceptReceived;
54 import net.pterodactylus.irc.event.DccDownloadFailed;
55 import net.pterodactylus.irc.event.DccDownloadFinished;
56 import net.pterodactylus.irc.event.DccSendReceived;
57 import net.pterodactylus.irc.event.KickedFromChannel;
58 import net.pterodactylus.irc.event.NicknameChanged;
59 import net.pterodactylus.irc.event.PrivateMessageReceived;
60 import net.pterodactylus.irc.event.PrivateNoticeReceived;
61 import net.pterodactylus.irc.event.ReplyReceived;
62 import net.pterodactylus.irc.util.RandomNickname;
63 import net.pterodactylus.xdcc.core.event.BotAdded;
64 import net.pterodactylus.xdcc.core.event.CoreStarted;
65 import net.pterodactylus.xdcc.core.event.DownloadFailed;
66 import net.pterodactylus.xdcc.core.event.DownloadFinished;
67 import net.pterodactylus.xdcc.core.event.DownloadStarted;
68 import net.pterodactylus.xdcc.core.event.GenericError;
69 import net.pterodactylus.xdcc.core.event.GenericMessage;
70 import net.pterodactylus.xdcc.core.event.MessageReceived;
71 import net.pterodactylus.xdcc.data.Bot;
72 import net.pterodactylus.xdcc.data.Channel;
73 import net.pterodactylus.xdcc.data.ConnectedNetwork;
74 import net.pterodactylus.xdcc.data.Download;
75 import net.pterodactylus.xdcc.data.Network;
76 import net.pterodactylus.xdcc.data.Pack;
77 import net.pterodactylus.xdcc.data.Server;
79 import com.google.common.base.Optional;
80 import com.google.common.base.Predicate;
81 import com.google.common.collect.FluentIterable;
82 import com.google.common.collect.HashBasedTable;
83 import com.google.common.collect.HashMultimap;
84 import com.google.common.collect.ImmutableList;
85 import com.google.common.collect.ImmutableSet;
86 import com.google.common.collect.Lists;
87 import com.google.common.collect.Maps;
88 import com.google.common.collect.Multimap;
89 import com.google.common.collect.Sets;
90 import com.google.common.collect.Table;
91 import com.google.common.eventbus.EventBus;
92 import com.google.common.eventbus.Subscribe;
93 import com.google.common.io.Closeables;
94 import com.google.common.util.concurrent.AbstractExecutionThreadService;
95 import com.google.inject.Inject;
96 import org.apache.log4j.Logger;
99 * The core of XDCC Downloader.
101 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
103 public class Core extends AbstractExecutionThreadService {
106 private static final Logger logger = Logger.getLogger(Core.class.getName());
108 private final Object syncObject = new Object();
109 /** The event bus. */
110 private final EventBus eventBus;
111 private final ConnectionFactory connectionFactory;
112 private final ChannelBanManager channelBanManager =
113 new ChannelBanManager();
115 /** The temporary directory to download files to. */
116 private final String temporaryDirectory;
118 /** The directory to move finished downloads to. */
119 private final String finalDirectory;
121 /** The channels that should be monitored. */
122 private final Collection<Channel> channels = Sets.newHashSet();
124 /** The channels that are currentlymonitored. */
125 private final Collection<Channel> joinedChannels = Sets.newHashSet();
127 /** The channels that are joined but not configured. */
128 private final Collection<Channel> extraChannels = Sets.newHashSet();
130 /** The current network connections. */
131 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
133 /** The currently known bots. */
134 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
136 /** The current downloads. */
137 private final Multimap<String, Download> downloads = HashMultimap.create();
139 /** The current DCC receivers. */
140 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
143 * Creates a new core.
147 * @param temporaryDirectory
148 * The directory to download files to
149 * @param finalDirectory
150 * The directory to move finished files to
153 public Core(EventBus eventBus, ConnectionFactory connectionFactory, String temporaryDirectory, String finalDirectory) {
154 this.eventBus = eventBus;
155 this.connectionFactory = connectionFactory;
156 this.temporaryDirectory = temporaryDirectory;
157 this.finalDirectory = finalDirectory;
165 * Returns all currently known connections.
167 * @return All currently known connections
169 public Collection<Connection> connections() {
170 return networkConnections.values();
174 * Returns all defined networks.
176 * @return All defined networks
178 public Collection<Network> networks() {
179 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
183 * Returns all connected networks.
185 * @return All connected networks
187 public Collection<ConnectedNetwork> connectedNetworks() {
188 return networkConnections.entrySet().stream().map((entry) -> {
189 Network network = entry.getKey();
190 Collection<Bot> bots = networkBots.row(network).values();
191 int packCount = bots.stream().mapToInt((bot) -> bot.packs().size()).reduce((a, b) -> a + b).orElse(0);
192 return new ConnectedNetwork(network, entry.getValue().hostname(),
193 entry.getValue().port(), entry.getValue().nickname(),
195 .filter((channel) -> channel.network()
198 .collect(Collectors.<String>toList()),
199 extraChannels.stream()
200 .filter((channel) -> channel.network()
203 .collect(Collectors.<String>toList()),
204 bots.size(), packCount);
205 }).collect(Collectors.<ConnectedNetwork>toList());
209 * Returns all configured channels. Due to various circumstances, configured
210 * channels might not actually be joined.
212 * @return All configured channels
214 public Collection<Channel> channels() {
215 return ImmutableSet.copyOf(channels);
219 * Returns all currently joined channels.
221 * @return All currently joined channels
223 public Collection<Channel> joinedChannels() {
224 return ImmutableSet.copyOf(joinedChannels);
228 * Returns all currently joined channels that are not configured.
230 * @return All currently joined but not configured channels
232 public Collection<Channel> extraChannels() {
233 return ImmutableSet.copyOf(extraChannels);
237 * Returns all currently known bots.
239 * @return All currently known bots
241 public Collection<Bot> bots() {
242 return networkBots.values();
246 * Returns all currently running downloads.
248 * @return All currently running downloads
250 public Collection<Download> downloads() {
251 return downloads.values();
259 * Adds a channel to monitor.
262 * The channel to monitor
264 public void addChannel(Channel channel) {
265 channels.add(channel);
269 * Fetches the given pack from the given bot.
272 * The bot to fetch the pack from
276 public void fetch(Bot bot, Pack pack) {
277 Connection connection = networkConnections.get(bot.network());
278 if (connection == null) {
282 /* check if we are already downloading the file? */
283 if (downloads.containsKey(pack.name())) {
284 Collection<Download> packDownloads = downloads.get(pack.name());
285 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
286 if (!runningDownloads.isEmpty()) {
287 Download download = runningDownloads.iterator().next();
288 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
291 StringBuilder bots = new StringBuilder();
292 for (Download download : packDownloads) {
293 if (bots.length() > 0) {
296 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
298 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
301 Download download = new Download(bot, pack);
302 downloads.put(pack.name(), download);
305 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
306 } catch (IOException ioe1) {
307 logger.warn("Could not send message to bot!", ioe1);
312 * Cancels the download of the given pack from the given bot.
315 * The bot the pack is being downloaded from
317 * The pack being downloaded
319 public void cancelDownload(Bot bot, Pack pack) {
320 Optional<Download> download = getDownload(pack, bot);
321 if (!download.isPresent()) {
325 /* get connection. */
326 Connection connection = networkConnections.get(bot.network());
327 if (connection == null) {
328 /* request for unknown network? */
332 /* stop the DCC receiver. */
333 if (download.get().dccReceiver() != null) {
334 download.get().dccReceiver().stop();
336 /* remove download if it hasn’t started yet. */
337 downloads.remove(pack.name(), download.get());
340 /* remove the request from the bot, too. */
342 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
343 } catch (IOException ioe1) {
344 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
349 * Closes the given connection.
352 * The connection to close
354 public void closeConnection(Connection connection) {
357 } catch (IOException ioe1) {
363 // ABSTRACTIDLESERVICE METHODS
367 protected void startUp() {
368 for (Channel channel : channels) {
369 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
370 connectNetwork(channel.network());
373 /* notify listeners. */
374 eventBus.post(new CoreStarted(this));
378 protected void run() throws Exception {
379 while (isRunning()) {
380 synchronized (syncObject) {
382 syncObject.wait(TimeUnit.MINUTES.toMillis(1));
383 } catch (InterruptedException ie1) {
391 /* find channels that should be monitored but are not. */
392 for (Channel channel : channels) {
393 if (joinedChannels.contains(channel)) {
397 /* are we banned from this channel? */
398 if (channelBanManager.isBanned(channel)) {
402 connectNetwork(channel.network());
403 Connection connection = networkConnections.get(channel.network());
404 if (connection.established()) {
405 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
407 connection.joinChannel(channel.name());
408 } catch (IOException ioe1) {
409 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
417 protected void triggerShutdown() {
418 synchronized (syncObject) {
419 syncObject.notifyAll();
428 * Starts a new connection for the given network if no such connection exists
432 * The network to connect to
434 private void connectNetwork(Network network) {
435 if (!networkConnections.containsKey(network)) {
436 /* select a random server. */
437 List<Server> servers = Lists.newArrayList(network.servers());
438 if (servers.isEmpty()) {
439 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
442 Server server = servers.get((int) (Math.random() * servers.size()));
443 Connection connection = connectionFactory.createConnection(server.hostname(),
444 server.unencryptedPorts().iterator().next());
445 connection.username(RandomNickname.get()).realName(RandomNickname.get());
446 networkConnections.put(network, connection);
452 * Removes the given connection and all its channels and bots.
455 * The connection to remove
457 private void removeConnection(Connection connection) {
458 Optional<Network> network = getNetwork(connection);
459 if (!network.isPresent()) {
462 if (!connection.established()) {
466 /* find all channels that need to be removed. */
467 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
468 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
469 Channel joinedChannel = channelIterator.next();
470 if (!joinedChannel.network().equals(network.get())) {
474 channelIterator.remove();
478 /* now remove all bots for that network. */
479 Map<String, Bot> bots = networkBots.row(network.get());
480 int botCount = bots.size();
482 for (Bot bot : bots.values()) {
483 packCount += bot.packs().size();
486 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
488 /* now remove the network. */
489 networkConnections.remove(network.get());
497 * If a connection to a network has been established, the channels associated
498 * with this network are joined.
500 * @param connectionEstablished
501 * The connection established event
504 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
506 /* get network for connection. */
507 Optional<Network> network = getNetwork(connectionEstablished.connection());
510 if (!network.isPresent()) {
511 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
515 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
517 /* join all channels on this network. */
518 for (Channel channel : channels) {
519 if (channel.network().equals(network.get())) {
521 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
522 connectionEstablished.connection().joinChannel(channel.name());
523 } catch (IOException ioe1) {
524 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
531 * Remove all data stored for a network if the connection is closed.
533 * @param connectionClosed
534 * The connection closed event
537 public void connectionClosed(ConnectionClosed connectionClosed) {
538 removeConnection(connectionClosed.connection());
539 eventBus.post(new GenericMessage(String.format("Connection closed by %s.", connectionClosed.connection().hostname())));
543 * Remove all data stored for a network if the connection fails.
545 * @param connectionFailed
546 * The connection failed event
549 public void connectionFailed(ConnectionFailed connectionFailed) {
550 removeConnection(connectionFailed.connection());
551 eventBus.post(new GenericMessage(String.format("Could not connect to %s: %s.", connectionFailed.connection().hostname(), connectionFailed.cause())));
555 * Shows a message when a channel was joined by us.
557 * @param channelJoined
558 * The channel joined event
561 public void channelJoined(ChannelJoined channelJoined) {
562 if (channelJoined.connection().isSource(channelJoined.client())) {
563 Optional<Network> network = getNetwork(channelJoined.connection());
564 if (!network.isPresent()) {
568 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
569 if (!channel.isPresent()) {
570 /* it’s an extra channel. */
571 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
572 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
576 channelBanManager.unban(channel.get());
577 joinedChannels.add(channel.get());
578 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
583 public void channelNotJoined(ChannelNotJoined channelNotJoined) {
584 Optional<Network> network = getNetwork(channelNotJoined.connection());
585 if (!network.isPresent()) {
589 Optional<Channel> channel = getChannel(network.get(), channelNotJoined.channel());
590 if (!channel.isPresent()) {
591 eventBus.post(new GenericMessage(format("Could not join %s but didn’t try to join, either.", channel.get())));
595 /* remove all bots for this channel, we might have been kicked. */
596 Collection<Bot> botsToRemove = networkBots.row(network.get())
598 .filter(bot -> bot.channel()
599 .equalsIgnoreCase(channel.get().name()))
600 .collect(Collectors.toSet());
601 botsToRemove.stream()
602 .forEach(bot -> networkBots.row(network.get())
603 .remove(bot.name()));
605 if (channelNotJoined.reason() == registeredNicknamesOnly) {
606 channels.remove(channel.get());
607 eventBus.post(new GenericMessage(
608 format("Not trying to join %s anymore.", channel.get())));
611 if (channelNotJoined.reason() == banned) {
612 channelBanManager.ban(channel.get());
613 eventBus.post(new GenericMessage(
614 format("Banned from %s, suspending join for a day.",
619 eventBus.post(new GenericMessage(
620 format("Could not join %s: %s", channelNotJoined.channel(),
621 channelNotJoined.reason())));
625 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
628 * The channel left event
631 public void channelLeft(ChannelLeft channelLeft) {
632 Optional<Network> network = getNetwork(channelLeft.connection());
633 if (!network.isPresent()) {
637 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
639 /* maybe it was us? */
640 if (channelLeft.connection().isSource(channelLeft.client())) {
641 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
642 if (!channel.isPresent()) {
643 /* maybe it was an extra channel? */
644 channel = getExtraChannel(network.get(), channelLeft.channel());
645 if (!channel.isPresent()) {
646 /* okay, whatever. */
650 extraChannels.remove(channel);
652 channels.remove(channel.get());
655 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
661 networkBots.remove(network.get(), channelLeft.client().nick().get());
665 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
666 Optional<Network> network = getNetwork(kickedFromChannel.connection());
667 if (!network.isPresent()) {
671 /* have we been kicked? */
672 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
673 Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
674 if (!channel.isPresent()) {
675 /* maybe it was an extra channel? */
676 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
677 if (!channel.isPresent()) {
678 /* okay, whatever. */
682 extraChannels.remove(channel.get());
684 joinedChannels.remove(channel.get());
686 eventBus.post(new GenericMessage(format(
687 "Kicked from %s by %s: %s",
688 kickedFromChannel.channel(),
689 kickedFromChannel.kicker(),
690 kickedFromChannel.reason().or("<unknown>")
695 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
696 return connection.nickname().equalsIgnoreCase(nickname);
700 * Removes a client (which may be a bot) from the table of known bots.
703 * The client quit event
706 public void clientQuit(ClientQuit clientQuit) {
707 Optional<Network> network = getNetwork(clientQuit.connection());
708 if (!network.isPresent()) {
712 networkBots.remove(network.get(), clientQuit.client().nick().get());
716 * If the nickname of a bit changes, remove it from the old name and store it
717 * under the new name.
719 * @param nicknameChanged
720 * The nickname changed event
723 public void nicknameChanged(NicknameChanged nicknameChanged) {
724 Optional<Network> network = getNetwork(nicknameChanged.connection());
725 if (!network.isPresent()) {
729 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
734 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
738 * If a message on a channel is received, it is parsed for pack information
739 * with is then added to a bot.
741 * @param channelMessageReceived
742 * The channel message received event
745 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
746 String message = getDefaultInstance().clean(channelMessageReceived.message());
747 if (!message.startsWith("#")) {
748 /* most probably not a pack announcement. */
752 Optional<Network> network = getNetwork(channelMessageReceived.connection());
753 if (!network.isPresent()) {
754 /* message for unknown connection? */
758 /* parse pack information. */
759 Optional<Pack> pack = parsePack(message);
760 if (!pack.isPresent()) {
765 synchronized (networkBots) {
766 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
767 bot = new Bot(network.get(), channelMessageReceived.channel(),
768 channelMessageReceived.source().nick().get());
769 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
770 eventBus.post(new BotAdded(bot));
772 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
777 bot.addPack(pack.get());
778 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
782 * Forward all private messages to every console.
784 * @param privateMessageReceived
785 * The private message recevied event
788 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
789 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
793 * Sends a message to all console when a notice was received.
795 * @param privateNoticeReceived
796 * The notice received event
799 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
800 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
801 if (!network.isPresent()) {
805 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.source(), network.get(), privateNoticeReceived.text())));
809 * Starts a DCC download.
811 * @param dccSendReceived
815 public void dccSendReceived(final DccSendReceived dccSendReceived) {
816 final Optional<Network> network = getNetwork(dccSendReceived.connection());
817 if (!network.isPresent()) {
821 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
822 if (packDownloads.isEmpty()) {
823 /* unknown download, ignore. */
827 /* check if it’s already downloading. */
828 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
829 if (!runningDownloads.isEmpty()) {
830 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
834 /* locate the correct download. */
835 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
838 public boolean apply(Download download) {
839 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
843 /* we did not request this download. */
844 if (requestedDownload.isEmpty()) {
848 Download download = requestedDownload.iterator().next();
850 /* check if the file already exists. */
851 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
852 if (outputFile.exists()) {
853 long existingFileSize = outputFile.length();
855 /* file already complete? */
856 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
857 /* file is apparently already complete. just move it. */
858 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
859 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
861 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
864 /* remove download. */
865 downloads.removeAll(download.pack().name());
869 /* file not complete yet, DCC resume it. */
871 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
872 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
873 } catch (IOException ioe1) {
874 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
880 /* file does not exist, start the download. */
882 OutputStream fileOutputStream = new FileOutputStream(outputFile);
883 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
884 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
885 dccReceivers.add(dccReceiver);
887 eventBus.post(new DownloadStarted(download));
888 } catch (FileNotFoundException fnfe1) {
889 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
894 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
895 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
896 if (!network.isPresent()) {
900 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
901 if (packDownloads.isEmpty()) {
902 /* unknown download, ignore. */
906 /* check if it’s already downloading. */
907 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
908 if (!runningDownloads.isEmpty()) {
909 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
913 /* locate the correct download. */
914 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
917 public boolean apply(Download download) {
918 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
922 /* we did not request this download. */
923 if (requestedDownload.isEmpty()) {
927 Download download = requestedDownload.iterator().next();
930 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
931 if (outputFile.length() != dccAcceptReceived.position()) {
932 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
933 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()));
935 downloads.removeAll(download.pack().name());
938 OutputStream outputStream = new FileOutputStream(outputFile, true);
939 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
940 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
941 dccReceivers.add(dccReceiver);
943 eventBus.post(new DownloadStarted(download));
944 } catch (FileNotFoundException fnfe1) {
949 * Closes the output stream of the download and moves the file to the final
952 * @param dccDownloadFinished
953 * The DCC download finished event
956 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
958 /* locate the correct download. */
959 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
960 if (requestedDownload.isEmpty()) {
961 /* this seems wrong. */
962 logger.warn("Download finished but could not be located.");
965 Download download = requestedDownload.iterator().next();
968 download.outputStream().close();
969 File file = new File(download.filename());
970 file.renameTo(new File(finalDirectory, download.pack().name()));
971 eventBus.post(new DownloadFinished(download));
972 dccReceivers.remove(dccDownloadFinished.dccReceiver());
973 downloads.removeAll(download.pack().name());
974 } catch (IOException ioe1) {
975 /* TODO - handle all the errors. */
976 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
981 * Closes the output stream and notifies all listeners of the failure.
983 * @param dccDownloadFailed
984 * The DCC download failed event
987 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
989 /* locate the correct download. */
990 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
991 if (requestedDownload.isEmpty()) {
992 /* this seems wrong. */
993 logger.warn("Download finished but could not be located.");
996 Download download = requestedDownload.iterator().next();
999 Closeables.close(download.outputStream(), true);
1000 eventBus.post(new DownloadFailed(download));
1001 dccReceivers.remove(dccDownloadFailed.dccReceiver());
1002 downloads.removeAll(download.pack().name());
1003 } catch (IOException ioe1) {
1004 /* swallow silently. */
1009 public void replyReceived(ReplyReceived replyReceived) {
1010 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
1018 * Returns the download of the given pack from the given bot.
1021 * The pack being downloaded
1023 * The bot the pack is being downloaded from
1024 * @return The download, or {@link Optional#absent()} if the download could not
1027 private Optional<Download> getDownload(Pack pack, Bot bot) {
1028 if (!downloads.containsKey(pack.name())) {
1029 return Optional.absent();
1031 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
1032 if (download.bot().equals(bot)) {
1033 return Optional.of(download);
1036 return Optional.absent();
1040 * Searches all current connections for the given connection, returning the
1041 * associated network.
1044 * The connection to get the network for
1045 * @return The network belonging to the connection, or {@link
1046 * Optional#absent()}
1048 private Optional<Network> getNetwork(Connection connection) {
1049 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
1050 if (networkConnectionEntry.getValue().equals(connection)) {
1051 return Optional.of(networkConnectionEntry.getKey());
1054 return Optional.absent();
1058 * Returns the configured channel for the given network and name.
1061 * The network the channel is located on
1062 * @param channelName
1063 * The name of the channel
1064 * @return The configured channel, or {@link Optional#absent()} if no
1065 * configured channel matching the given network and name was found
1067 public Optional<Channel> getChannel(Network network, String channelName) {
1068 for (Channel channel : channels) {
1069 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1070 return Optional.of(channel);
1073 return Optional.absent();
1077 * Returns the extra channel for the given network and name.
1080 * The network the channel is located on
1081 * @param channelName
1082 * The name of the channel
1083 * @return The extra channel, or {@link Optional#absent()} if no extra channel
1084 * matching the given network and name was found
1086 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1087 for (Channel channel : extraChannels) {
1088 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1089 return Optional.of(channel);
1092 return Optional.absent();
1096 * Parses {@link Pack} information from the given message.
1099 * The message to parse pack information from
1100 * @return The parsed pack, or {@link Optional#absent()} if the message could
1101 * not be parsed into a pack
1103 private Optional<Pack> parsePack(String message) {
1104 int squareOpen = message.indexOf('[');
1105 int squareClose = message.indexOf(']', squareOpen);
1106 if ((squareOpen == -1) && (squareClose == -1)) {
1107 return Optional.absent();
1109 String packSize = message.substring(squareOpen + 1, squareClose);
1110 String packName = message.substring(message.lastIndexOf(' ') + 1);
1111 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1112 return Optional.of(new Pack(packIndex, packSize, packName));