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 /** The event bus. */
109 private final EventBus eventBus;
110 private final ConnectionFactory connectionFactory;
111 private final ChannelBanManager channelBanManager =
112 new ChannelBanManager();
114 /** The temporary directory to download files to. */
115 private final String temporaryDirectory;
117 /** The directory to move finished downloads to. */
118 private final String finalDirectory;
120 /** The channels that should be monitored. */
121 private final Collection<Channel> channels = Sets.newHashSet();
123 /** The channels that are currentlymonitored. */
124 private final Collection<Channel> joinedChannels = Sets.newHashSet();
126 /** The channels that are joined but not configured. */
127 private final Collection<Channel> extraChannels = Sets.newHashSet();
129 /** The current network connections. */
130 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
132 /** The currently known bots. */
133 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
135 /** The current downloads. */
136 private final Multimap<String, Download> downloads = HashMultimap.create();
138 /** The current DCC receivers. */
139 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
142 * Creates a new core.
146 * @param temporaryDirectory
147 * The directory to download files to
148 * @param finalDirectory
149 * The directory to move finished files to
152 public Core(EventBus eventBus, ConnectionFactory connectionFactory, String temporaryDirectory, String finalDirectory) {
153 this.eventBus = eventBus;
154 this.connectionFactory = connectionFactory;
155 this.temporaryDirectory = temporaryDirectory;
156 this.finalDirectory = finalDirectory;
164 * Returns all currently known connections.
166 * @return All currently known connections
168 public Collection<Connection> connections() {
169 return networkConnections.values();
173 * Returns all defined networks.
175 * @return All defined networks
177 public Collection<Network> networks() {
178 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
182 * Returns all connected networks.
184 * @return All connected networks
186 public Collection<ConnectedNetwork> connectedNetworks() {
187 return networkConnections.entrySet().stream().map((entry) -> {
188 Network network = entry.getKey();
189 Collection<Bot> bots = networkBots.row(network).values();
190 int packCount = bots.stream().mapToInt((bot) -> bot.packs().size()).reduce((a, b) -> a + b).orElse(0);
191 return new ConnectedNetwork(network, entry.getValue().hostname(),
192 entry.getValue().port(), entry.getValue().nickname(),
194 .filter((channel) -> channel.network()
197 .collect(Collectors.<String>toList()),
198 extraChannels.stream()
199 .filter((channel) -> channel.network()
202 .collect(Collectors.<String>toList()),
203 bots.size(), packCount);
204 }).collect(Collectors.<ConnectedNetwork>toList());
208 * Returns all configured channels. Due to various circumstances, configured
209 * channels might not actually be joined.
211 * @return All configured channels
213 public Collection<Channel> channels() {
214 return ImmutableSet.copyOf(channels);
218 * Returns all currently joined channels.
220 * @return All currently joined channels
222 public Collection<Channel> joinedChannels() {
223 return ImmutableSet.copyOf(joinedChannels);
227 * Returns all currently joined channels that are not configured.
229 * @return All currently joined but not configured channels
231 public Collection<Channel> extraChannels() {
232 return ImmutableSet.copyOf(extraChannels);
236 * Returns all currently known bots.
238 * @return All currently known bots
240 public Collection<Bot> bots() {
241 return networkBots.values();
245 * Returns all currently running downloads.
247 * @return All currently running downloads
249 public Collection<Download> downloads() {
250 return downloads.values();
258 * Adds a channel to monitor.
261 * The channel to monitor
263 public void addChannel(Channel channel) {
264 channels.add(channel);
268 * Fetches the given pack from the given bot.
271 * The bot to fetch the pack from
275 public void fetch(Bot bot, Pack pack) {
276 Connection connection = networkConnections.get(bot.network());
277 if (connection == null) {
281 /* check if we are already downloading the file? */
282 if (downloads.containsKey(pack.name())) {
283 Collection<Download> packDownloads = downloads.get(pack.name());
284 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
285 if (!runningDownloads.isEmpty()) {
286 Download download = runningDownloads.iterator().next();
287 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
290 StringBuilder bots = new StringBuilder();
291 for (Download download : packDownloads) {
292 if (bots.length() > 0) {
295 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
297 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
300 Download download = new Download(bot, pack);
301 downloads.put(pack.name(), download);
304 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
305 } catch (IOException ioe1) {
306 logger.warn("Could not send message to bot!", ioe1);
311 * Cancels the download of the given pack from the given bot.
314 * The bot the pack is being downloaded from
316 * The pack being downloaded
318 public void cancelDownload(Bot bot, Pack pack) {
319 Optional<Download> download = getDownload(pack, bot);
320 if (!download.isPresent()) {
324 /* get connection. */
325 Connection connection = networkConnections.get(bot.network());
326 if (connection == null) {
327 /* request for unknown network? */
331 /* stop the DCC receiver. */
332 if (download.get().dccReceiver() != null) {
333 download.get().dccReceiver().stop();
335 /* remove download if it hasn’t started yet. */
336 downloads.remove(pack.name(), download.get());
339 /* remove the request from the bot, too. */
341 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
342 } catch (IOException ioe1) {
343 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
348 * Closes the given connection.
351 * The connection to close
353 public void closeConnection(Connection connection) {
356 } catch (IOException ioe1) {
362 // ABSTRACTIDLESERVICE METHODS
366 protected void startUp() {
367 for (Channel channel : channels) {
368 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
369 connectNetwork(channel.network());
372 /* notify listeners. */
373 eventBus.post(new CoreStarted(this));
377 protected void run() throws Exception {
378 while (isRunning()) {
380 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
381 } catch (InterruptedException ie1) {
385 /* find channels that should be monitored but are not. */
386 for (Channel channel : channels) {
387 if (joinedChannels.contains(channel)) {
391 /* are we banned from this channel? */
392 if (channelBanManager.isBanned(channel)) {
396 connectNetwork(channel.network());
397 Connection connection = networkConnections.get(channel.network());
398 if (connection.established()) {
399 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
401 connection.joinChannel(channel.name());
402 } catch (IOException ioe1) {
403 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
411 protected void shutDown() {
419 * Starts a new connection for the given network if no such connection exists
423 * The network to connect to
425 private void connectNetwork(Network network) {
426 if (!networkConnections.containsKey(network)) {
427 /* select a random server. */
428 List<Server> servers = Lists.newArrayList(network.servers());
429 if (servers.isEmpty()) {
430 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
433 Server server = servers.get((int) (Math.random() * servers.size()));
434 Connection connection = connectionFactory.createConnection(server.hostname(),
435 server.unencryptedPorts().iterator().next());
436 connection.username(RandomNickname.get()).realName(RandomNickname.get());
437 networkConnections.put(network, connection);
443 * Removes the given connection and all its channels and bots.
446 * The connection to remove
448 private void removeConnection(Connection connection) {
449 Optional<Network> network = getNetwork(connection);
450 if (!network.isPresent()) {
453 if (!connection.established()) {
457 /* find all channels that need to be removed. */
458 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
459 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
460 Channel joinedChannel = channelIterator.next();
461 if (!joinedChannel.network().equals(network.get())) {
465 channelIterator.remove();
469 /* now remove all bots for that network. */
470 Map<String, Bot> bots = networkBots.row(network.get());
471 int botCount = bots.size();
473 for (Bot bot : bots.values()) {
474 packCount += bot.packs().size();
477 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
479 /* now remove the network. */
480 networkConnections.remove(network.get());
488 * If a connection to a network has been established, the channels associated
489 * with this network are joined.
491 * @param connectionEstablished
492 * The connection established event
495 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
497 /* get network for connection. */
498 Optional<Network> network = getNetwork(connectionEstablished.connection());
501 if (!network.isPresent()) {
502 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
506 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
508 /* join all channels on this network. */
509 for (Channel channel : channels) {
510 if (channel.network().equals(network.get())) {
512 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
513 connectionEstablished.connection().joinChannel(channel.name());
514 } catch (IOException ioe1) {
515 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
522 * Remove all data stored for a network if the connection is closed.
524 * @param connectionClosed
525 * The connection closed event
528 public void connectionClosed(ConnectionClosed connectionClosed) {
529 removeConnection(connectionClosed.connection());
533 * Remove all data stored for a network if the connection fails.
535 * @param connectionFailed
536 * The connection failed event
539 public void connectionFailed(ConnectionFailed connectionFailed) {
540 removeConnection(connectionFailed.connection());
544 * Shows a message when a channel was joined by us.
546 * @param channelJoined
547 * The channel joined event
550 public void channelJoined(ChannelJoined channelJoined) {
551 if (channelJoined.connection().isSource(channelJoined.client())) {
552 Optional<Network> network = getNetwork(channelJoined.connection());
553 if (!network.isPresent()) {
557 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
558 if (!channel.isPresent()) {
559 /* it’s an extra channel. */
560 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
561 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
565 channelBanManager.unban(channel.get());
566 joinedChannels.add(channel.get());
567 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
572 public void channelNotJoined(ChannelNotJoined channelNotJoined) {
573 Optional<Network> network = getNetwork(channelNotJoined.connection());
574 if (!network.isPresent()) {
578 Optional<Channel> channel = getChannel(network.get(), channelNotJoined.channel());
579 if (!channel.isPresent()) {
580 eventBus.post(new GenericMessage(format("Could not join %s but didn’t try to join, either.", channel.get())));
584 /* remove all bots for this channel, we might have been kicked. */
585 Collection<Bot> botsToRemove = networkBots.row(network.get())
587 .filter(bot -> bot.channel()
588 .equalsIgnoreCase(channel.get().name()))
589 .collect(Collectors.toSet());
590 botsToRemove.stream()
591 .forEach(bot -> networkBots.row(network.get())
592 .remove(bot.name()));
594 if (channelNotJoined.reason() == registeredNicknamesOnly) {
595 channels.remove(channel.get());
596 eventBus.post(new GenericMessage(
597 format("Not trying to join %s anymore.", channel.get())));
600 if (channelNotJoined.reason() == banned) {
601 channelBanManager.ban(channel.get());
602 eventBus.post(new GenericMessage(
603 format("Banned from %s, suspending join for a day.",
608 eventBus.post(new GenericMessage(
609 format("Could not join %s: %s", channelNotJoined.channel(),
610 channelNotJoined.reason())));
614 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
617 * The channel left event
620 public void channelLeft(ChannelLeft channelLeft) {
621 Optional<Network> network = getNetwork(channelLeft.connection());
622 if (!network.isPresent()) {
626 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
628 /* maybe it was us? */
629 if (channelLeft.connection().isSource(channelLeft.client())) {
630 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
631 if (!channel.isPresent()) {
632 /* maybe it was an extra channel? */
633 channel = getExtraChannel(network.get(), channelLeft.channel());
634 if (!channel.isPresent()) {
635 /* okay, whatever. */
639 extraChannels.remove(channel);
641 channels.remove(channel.get());
644 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
650 networkBots.remove(network.get(), channelLeft.client().nick().get());
654 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
655 Optional<Network> network = getNetwork(kickedFromChannel.connection());
656 if (!network.isPresent()) {
660 /* have we been kicked? */
661 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
662 Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
663 if (!channel.isPresent()) {
664 /* maybe it was an extra channel? */
665 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
666 if (!channel.isPresent()) {
667 /* okay, whatever. */
671 extraChannels.remove(channel);
673 channels.remove(channel.get());
675 eventBus.post(new GenericMessage(format(
676 "Kicked from %s by %s: %s",
677 kickedFromChannel.channel(),
678 kickedFromChannel.kicker(),
679 kickedFromChannel.reason().or("<unknown>")
684 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
685 return connection.nickname().equalsIgnoreCase(nickname);
689 * Removes a client (which may be a bot) from the table of known bots.
692 * The client quit event
695 public void clientQuit(ClientQuit clientQuit) {
696 Optional<Network> network = getNetwork(clientQuit.connection());
697 if (!network.isPresent()) {
701 networkBots.remove(network.get(), clientQuit.client().nick().get());
705 * If the nickname of a bit changes, remove it from the old name and store it
706 * under the new name.
708 * @param nicknameChanged
709 * The nickname changed event
712 public void nicknameChanged(NicknameChanged nicknameChanged) {
713 Optional<Network> network = getNetwork(nicknameChanged.connection());
714 if (!network.isPresent()) {
718 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
723 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
727 * If a message on a channel is received, it is parsed for pack information
728 * with is then added to a bot.
730 * @param channelMessageReceived
731 * The channel message received event
734 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
735 String message = getDefaultInstance().clean(channelMessageReceived.message());
736 if (!message.startsWith("#")) {
737 /* most probably not a pack announcement. */
741 Optional<Network> network = getNetwork(channelMessageReceived.connection());
742 if (!network.isPresent()) {
743 /* message for unknown connection? */
747 /* parse pack information. */
748 Optional<Pack> pack = parsePack(message);
749 if (!pack.isPresent()) {
754 synchronized (networkBots) {
755 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
756 bot = new Bot(network.get(), channelMessageReceived.channel(),
757 channelMessageReceived.source().nick().get());
758 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
759 eventBus.post(new BotAdded(bot));
761 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
766 bot.addPack(pack.get());
767 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
771 * Forward all private messages to every console.
773 * @param privateMessageReceived
774 * The private message recevied event
777 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
778 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
782 * Sends a message to all console when a notice was received.
784 * @param privateNoticeReceived
785 * The notice received event
788 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
789 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
790 if (!network.isPresent()) {
794 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.source(), network.get(), privateNoticeReceived.text())));
798 * Starts a DCC download.
800 * @param dccSendReceived
804 public void dccSendReceived(final DccSendReceived dccSendReceived) {
805 final Optional<Network> network = getNetwork(dccSendReceived.connection());
806 if (!network.isPresent()) {
810 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
811 if (packDownloads.isEmpty()) {
812 /* unknown download, ignore. */
816 /* check if it’s already downloading. */
817 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
818 if (!runningDownloads.isEmpty()) {
819 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
823 /* locate the correct download. */
824 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
827 public boolean apply(Download download) {
828 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
832 /* we did not request this download. */
833 if (requestedDownload.isEmpty()) {
837 Download download = requestedDownload.iterator().next();
839 /* check if the file already exists. */
840 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
841 if (outputFile.exists()) {
842 long existingFileSize = outputFile.length();
844 /* file already complete? */
845 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
846 /* file is apparently already complete. just move it. */
847 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
848 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
850 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
853 /* remove download. */
854 downloads.removeAll(download.pack().name());
858 /* file not complete yet, DCC resume it. */
860 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
861 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
862 } catch (IOException ioe1) {
863 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
869 /* file does not exist, start the download. */
871 OutputStream fileOutputStream = new FileOutputStream(outputFile);
872 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
873 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
874 dccReceivers.add(dccReceiver);
876 eventBus.post(new DownloadStarted(download));
877 } catch (FileNotFoundException fnfe1) {
878 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
883 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
884 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
885 if (!network.isPresent()) {
889 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
890 if (packDownloads.isEmpty()) {
891 /* unknown download, ignore. */
895 /* check if it’s already downloading. */
896 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
897 if (!runningDownloads.isEmpty()) {
898 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
902 /* locate the correct download. */
903 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
906 public boolean apply(Download download) {
907 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
911 /* we did not request this download. */
912 if (requestedDownload.isEmpty()) {
916 Download download = requestedDownload.iterator().next();
919 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
920 if (outputFile.length() != dccAcceptReceived.position()) {
921 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
922 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()));
924 downloads.removeAll(download.pack().name());
927 OutputStream outputStream = new FileOutputStream(outputFile, true);
928 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
929 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
930 dccReceivers.add(dccReceiver);
932 eventBus.post(new DownloadStarted(download));
933 } catch (FileNotFoundException fnfe1) {
938 * Closes the output stream of the download and moves the file to the final
941 * @param dccDownloadFinished
942 * The DCC download finished event
945 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
947 /* locate the correct download. */
948 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
949 if (requestedDownload.isEmpty()) {
950 /* this seems wrong. */
951 logger.warn("Download finished but could not be located.");
954 Download download = requestedDownload.iterator().next();
957 download.outputStream().close();
958 File file = new File(download.filename());
959 file.renameTo(new File(finalDirectory, download.pack().name()));
960 eventBus.post(new DownloadFinished(download));
961 dccReceivers.remove(dccDownloadFinished.dccReceiver());
962 downloads.removeAll(download.pack().name());
963 } catch (IOException ioe1) {
964 /* TODO - handle all the errors. */
965 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
970 * Closes the output stream and notifies all listeners of the failure.
972 * @param dccDownloadFailed
973 * The DCC download failed event
976 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
978 /* locate the correct download. */
979 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
980 if (requestedDownload.isEmpty()) {
981 /* this seems wrong. */
982 logger.warn("Download finished but could not be located.");
985 Download download = requestedDownload.iterator().next();
988 Closeables.close(download.outputStream(), true);
989 eventBus.post(new DownloadFailed(download));
990 dccReceivers.remove(dccDownloadFailed.dccReceiver());
991 downloads.removeAll(download.pack().name());
992 } catch (IOException ioe1) {
993 /* swallow silently. */
998 public void replyReceived(ReplyReceived replyReceived) {
999 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
1007 * Returns the download of the given pack from the given bot.
1010 * The pack being downloaded
1012 * The bot the pack is being downloaded from
1013 * @return The download, or {@link Optional#absent()} if the download could not
1016 private Optional<Download> getDownload(Pack pack, Bot bot) {
1017 if (!downloads.containsKey(pack.name())) {
1018 return Optional.absent();
1020 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
1021 if (download.bot().equals(bot)) {
1022 return Optional.of(download);
1025 return Optional.absent();
1029 * Searches all current connections for the given connection, returning the
1030 * associated network.
1033 * The connection to get the network for
1034 * @return The network belonging to the connection, or {@link
1035 * Optional#absent()}
1037 private Optional<Network> getNetwork(Connection connection) {
1038 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
1039 if (networkConnectionEntry.getValue().equals(connection)) {
1040 return Optional.of(networkConnectionEntry.getKey());
1043 return Optional.absent();
1047 * Returns the configured channel for the given network and name.
1050 * The network the channel is located on
1051 * @param channelName
1052 * The name of the channel
1053 * @return The configured channel, or {@link Optional#absent()} if no
1054 * configured channel matching the given network and name was found
1056 public Optional<Channel> getChannel(Network network, String channelName) {
1057 for (Channel channel : channels) {
1058 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1059 return Optional.of(channel);
1062 return Optional.absent();
1066 * Returns the extra channel for the given network and name.
1069 * The network the channel is located on
1070 * @param channelName
1071 * The name of the channel
1072 * @return The extra channel, or {@link Optional#absent()} if no extra channel
1073 * matching the given network and name was found
1075 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1076 for (Channel channel : extraChannels) {
1077 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1078 return Optional.of(channel);
1081 return Optional.absent();
1085 * Parses {@link Pack} information from the given message.
1088 * The message to parse pack information from
1089 * @return The parsed pack, or {@link Optional#absent()} if the message could
1090 * not be parsed into a pack
1092 private Optional<Pack> parsePack(String message) {
1093 int squareOpen = message.indexOf('[');
1094 int squareClose = message.indexOf(']', squareOpen);
1095 if ((squareOpen == -1) && (squareClose == -1)) {
1096 return Optional.absent();
1098 String packSize = message.substring(squareOpen + 1, squareClose);
1099 String packName = message.substring(message.lastIndexOf(' ') + 1);
1100 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1101 return Optional.of(new Pack(packIndex, packSize, packName));