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.util.MessageCleaner.getDefaultInstance;
22 import static net.pterodactylus.xdcc.data.Channel.TO_NETWORK;
23 import static net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
26 import java.io.FileNotFoundException;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.io.OutputStream;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.Iterator;
33 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.concurrent.TimeUnit;
38 import net.pterodactylus.irc.Connection;
39 import net.pterodactylus.irc.ConnectionBuilder;
40 import net.pterodactylus.irc.DccReceiver;
41 import net.pterodactylus.irc.event.ChannelJoined;
42 import net.pterodactylus.irc.event.ChannelLeft;
43 import net.pterodactylus.irc.event.ChannelMessageReceived;
44 import net.pterodactylus.irc.event.ChannelNotJoined;
45 import net.pterodactylus.irc.event.ClientQuit;
46 import net.pterodactylus.irc.event.ConnectionClosed;
47 import net.pterodactylus.irc.event.ConnectionEstablished;
48 import net.pterodactylus.irc.event.ConnectionFailed;
49 import net.pterodactylus.irc.event.DccAcceptReceived;
50 import net.pterodactylus.irc.event.DccDownloadFailed;
51 import net.pterodactylus.irc.event.DccDownloadFinished;
52 import net.pterodactylus.irc.event.DccSendReceived;
53 import net.pterodactylus.irc.event.KickedFromChannel;
54 import net.pterodactylus.irc.event.NicknameChanged;
55 import net.pterodactylus.irc.event.PrivateMessageReceived;
56 import net.pterodactylus.irc.event.PrivateNoticeReceived;
57 import net.pterodactylus.irc.event.ReplyReceived;
58 import net.pterodactylus.irc.util.RandomNickname;
59 import net.pterodactylus.xdcc.core.event.BotAdded;
60 import net.pterodactylus.xdcc.core.event.CoreStarted;
61 import net.pterodactylus.xdcc.core.event.DownloadFailed;
62 import net.pterodactylus.xdcc.core.event.DownloadFinished;
63 import net.pterodactylus.xdcc.core.event.DownloadStarted;
64 import net.pterodactylus.xdcc.core.event.GenericError;
65 import net.pterodactylus.xdcc.core.event.GenericMessage;
66 import net.pterodactylus.xdcc.core.event.MessageReceived;
67 import net.pterodactylus.xdcc.data.Bot;
68 import net.pterodactylus.xdcc.data.Channel;
69 import net.pterodactylus.xdcc.data.Download;
70 import net.pterodactylus.xdcc.data.Network;
71 import net.pterodactylus.xdcc.data.Pack;
72 import net.pterodactylus.xdcc.data.Server;
74 import com.google.common.base.Function;
75 import com.google.common.base.Optional;
76 import com.google.common.base.Predicate;
77 import com.google.common.collect.FluentIterable;
78 import com.google.common.collect.HashBasedTable;
79 import com.google.common.collect.HashMultimap;
80 import com.google.common.collect.ImmutableList;
81 import com.google.common.collect.ImmutableSet;
82 import com.google.common.collect.Lists;
83 import com.google.common.collect.Maps;
84 import com.google.common.collect.Multimap;
85 import com.google.common.collect.Sets;
86 import com.google.common.collect.Table;
87 import com.google.common.eventbus.EventBus;
88 import com.google.common.eventbus.Subscribe;
89 import com.google.common.io.Closeables;
90 import com.google.common.util.concurrent.AbstractExecutionThreadService;
91 import com.google.inject.Inject;
92 import org.apache.log4j.Logger;
95 * The core of XDCC Downloader.
97 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
99 public class Core extends AbstractExecutionThreadService {
102 private static final Logger logger = Logger.getLogger(Core.class.getName());
104 /** The event bus. */
105 private final EventBus eventBus;
107 /** The temporary directory to download files to. */
108 private final String temporaryDirectory;
110 /** The directory to move finished downloads to. */
111 private final String finalDirectory;
113 /** The channels that should be monitored. */
114 private final Collection<Channel> channels = Sets.newHashSet();
116 /** The channels that are currentlymonitored. */
117 private final Collection<Channel> joinedChannels = Sets.newHashSet();
119 /** The channels that are joined but not configured. */
120 private final Collection<Channel> extraChannels = Sets.newHashSet();
122 /** The current network connections. */
123 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
125 /** The currently known bots. */
126 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
128 /** The current downloads. */
129 private final Multimap<String, Download> downloads = HashMultimap.create();
131 /** The current DCC receivers. */
132 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
135 * Creates a new core.
139 * @param temporaryDirectory
140 * The directory to download files to
141 * @param finalDirectory
142 * The directory to move finished files to
145 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
146 this.eventBus = eventBus;
147 this.temporaryDirectory = temporaryDirectory;
148 this.finalDirectory = finalDirectory;
156 * Returns all currently known connections.
158 * @return All currently known connections
160 public Collection<Connection> connections() {
161 return networkConnections.values();
165 * Returns all defined networks.
167 * @return All defined networks
169 public Collection<Network> networks() {
170 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
174 * Returns all connected networks.
176 * @return All connected networks
178 public Collection<Network> connectedNetworks() {
179 return Lists.newArrayList(Optional.presentInstances(FluentIterable.from(networkConnections.values()).transform(new Function<Connection, Optional<Network>>() {
181 public Optional<Network> apply(Connection connection) {
182 return getNetwork(connection);
188 * Returns all configured channels. Due to various circumstances, configured
189 * channels might not actually be joined.
191 * @return All configured channels
193 public Collection<Channel> channels() {
194 return ImmutableSet.copyOf(channels);
198 * Returns all currently joined channels.
200 * @return All currently joined channels
202 public Collection<Channel> joinedChannels() {
203 return ImmutableSet.copyOf(joinedChannels);
207 * Returns all currently joined channels that are not configured.
209 * @return All currently joined but not configured channels
211 public Collection<Channel> extraChannels() {
212 return ImmutableSet.copyOf(extraChannels);
216 * Returns all currently known bots.
218 * @return All currently known bots
220 public Collection<Bot> bots() {
221 return networkBots.values();
225 * Returns all currently running downloads.
227 * @return All currently running downloads
229 public Collection<Download> downloads() {
230 return downloads.values();
238 * Adds a channel to monitor.
241 * The channel to monitor
243 public void addChannel(Channel channel) {
244 channels.add(channel);
248 * Fetches the given pack from the given bot.
251 * The bot to fetch the pack from
255 public void fetch(Bot bot, Pack pack) {
256 Connection connection = networkConnections.get(bot.network());
257 if (connection == null) {
261 /* check if we are already downloading the file? */
262 if (downloads.containsKey(pack.name())) {
263 Collection<Download> packDownloads = downloads.get(pack.name());
264 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
265 if (!runningDownloads.isEmpty()) {
266 Download download = runningDownloads.iterator().next();
267 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
270 StringBuilder bots = new StringBuilder();
271 for (Download download : packDownloads) {
272 if (bots.length() > 0) {
275 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
277 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
280 Download download = new Download(bot, pack);
281 downloads.put(pack.name(), download);
284 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
285 } catch (IOException ioe1) {
286 logger.warn("Could not send message to bot!", ioe1);
291 * Cancels the download of the given pack from the given bot.
294 * The bot the pack is being downloaded from
296 * The pack being downloaded
298 public void cancelDownload(Bot bot, Pack pack) {
299 Optional<Download> download = getDownload(pack, bot);
300 if (!download.isPresent()) {
304 /* get connection. */
305 Connection connection = networkConnections.get(bot.network());
306 if (connection == null) {
307 /* request for unknown network? */
311 /* stop the DCC receiver. */
312 if (download.get().dccReceiver() != null) {
313 download.get().dccReceiver().stop();
315 /* remove download if it hasn’t started yet. */
316 downloads.remove(pack.name(), download.get());
319 /* remove the request from the bot, too. */
321 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
322 } catch (IOException ioe1) {
323 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
328 * Closes the given connection.
331 * The connection to close
333 public void closeConnection(Connection connection) {
336 } catch (IOException ioe1) {
342 // ABSTRACTIDLESERVICE METHODS
346 protected void startUp() {
347 for (Channel channel : channels) {
348 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
349 connectNetwork(channel.network());
352 /* notify listeners. */
353 eventBus.post(new CoreStarted(this));
357 protected void run() throws Exception {
358 while (isRunning()) {
360 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
361 } catch (InterruptedException ie1) {
365 /* find channels that should be monitored but are not. */
366 for (Channel channel : channels) {
367 if (joinedChannels.contains(channel)) {
371 connectNetwork(channel.network());
372 Connection connection = networkConnections.get(channel.network());
373 if (connection.established()) {
374 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
376 connection.joinChannel(channel.name());
377 } catch (IOException ioe1) {
378 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
386 protected void shutDown() {
394 * Starts a new connection for the given network if no such connection exists
398 * The network to connect to
400 private void connectNetwork(Network network) {
401 if (!networkConnections.containsKey(network)) {
402 /* select a random server. */
403 List<Server> servers = Lists.newArrayList(network.servers());
404 if (servers.isEmpty()) {
405 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
408 Server server = servers.get((int) (Math.random() * servers.size()));
409 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
410 connection.username(RandomNickname.get()).realName(RandomNickname.get());
411 networkConnections.put(network, connection);
417 * Removes the given connection and all its channels and bots.
420 * The connection to remove
422 private void removeConnection(Connection connection) {
423 Optional<Network> network = getNetwork(connection);
424 if (!network.isPresent()) {
428 /* find all channels that need to be removed. */
429 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
430 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
431 Channel joinedChannel = channelIterator.next();
432 if (!joinedChannel.network().equals(network.get())) {
436 channelIterator.remove();
440 /* now remove all bots for that network. */
441 Map<String, Bot> bots = networkBots.row(network.get());
442 int botCount = bots.size();
444 for (Bot bot : bots.values()) {
445 packCount += bot.packs().size();
448 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
450 /* now remove the network. */
451 networkConnections.remove(network.get());
459 * If a connection to a network has been established, the channels associated
460 * with this network are joined.
462 * @param connectionEstablished
463 * The connection established event
466 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
468 /* get network for connection. */
469 Optional<Network> network = getNetwork(connectionEstablished.connection());
472 if (!network.isPresent()) {
473 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
477 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
479 /* join all channels on this network. */
480 for (Channel channel : channels) {
481 if (channel.network().equals(network.get())) {
483 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
484 connectionEstablished.connection().joinChannel(channel.name());
485 } catch (IOException ioe1) {
486 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
493 * Remove all data stored for a network if the connection is closed.
495 * @param connectionClosed
496 * The connection closed event
499 public void connectionClosed(ConnectionClosed connectionClosed) {
500 removeConnection(connectionClosed.connection());
504 * Remove all data stored for a network if the connection fails.
506 * @param connectionFailed
507 * The connection failed event
510 public void connectionFailed(ConnectionFailed connectionFailed) {
511 removeConnection(connectionFailed.connection());
515 * Shows a message when a channel was joined by us.
517 * @param channelJoined
518 * The channel joined event
521 public void channelJoined(ChannelJoined channelJoined) {
522 if (channelJoined.connection().isSource(channelJoined.client())) {
523 Optional<Network> network = getNetwork(channelJoined.connection());
524 if (!network.isPresent()) {
528 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
529 if (!channel.isPresent()) {
530 /* it’s an extra channel. */
531 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
532 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
536 joinedChannels.add(channel.get());
537 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
542 public void channelNotJoined(ChannelNotJoined channelNotJoined) {
543 Optional<Network> network = getNetwork(channelNotJoined.connection());
544 if (!network.isPresent()) {
548 eventBus.post(new GenericMessage(
549 format("Could not join %s/%s: %s", channelNotJoined.channel(),
550 network.get(), channelNotJoined.reason())));
554 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
557 * The channel left event
560 public void channelLeft(ChannelLeft channelLeft) {
561 Optional<Network> network = getNetwork(channelLeft.connection());
562 if (!network.isPresent()) {
566 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
568 /* maybe it was us? */
569 if (channelLeft.connection().isSource(channelLeft.client())) {
570 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
571 if (!channel.isPresent()) {
572 /* maybe it was an extra channel? */
573 channel = getExtraChannel(network.get(), channelLeft.channel());
574 if (!channel.isPresent()) {
575 /* okay, whatever. */
579 extraChannels.remove(channel);
581 channels.remove(channel.get());
584 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
590 networkBots.remove(network.get(), channelLeft.client().nick().get());
594 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
595 Optional<Network> network = getNetwork(kickedFromChannel.connection());
596 if (!network.isPresent()) {
600 /* have we been kicked? */
601 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
602 Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
603 if (!channel.isPresent()) {
604 /* maybe it was an extra channel? */
605 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
606 if (!channel.isPresent()) {
607 /* okay, whatever. */
611 extraChannels.remove(channel);
613 channels.remove(channel.get());
615 eventBus.post(new GenericMessage(format(
616 "Kicked from %s/%s by %s: %s",
617 kickedFromChannel.channel(), network.get(),
618 kickedFromChannel.kicker(),
619 kickedFromChannel.reason().or("<unknown>")
624 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
625 return connection.nickname().equalsIgnoreCase(nickname);
629 * Removes a client (which may be a bot) from the table of known bots.
632 * The client quit event
635 public void clientQuit(ClientQuit clientQuit) {
636 Optional<Network> network = getNetwork(clientQuit.connection());
637 if (!network.isPresent()) {
641 networkBots.remove(network.get(), clientQuit.client().nick().get());
645 * If the nickname of a bit changes, remove it from the old name and store it
646 * under the new name.
648 * @param nicknameChanged
649 * The nickname changed event
652 public void nicknameChanged(NicknameChanged nicknameChanged) {
653 Optional<Network> network = getNetwork(nicknameChanged.connection());
654 if (!network.isPresent()) {
658 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
663 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
667 * If a message on a channel is received, it is parsed for pack information
668 * with is then added to a bot.
670 * @param channelMessageReceived
671 * The channel message received event
674 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
675 String message = getDefaultInstance().clean(channelMessageReceived.message());
676 if (!message.startsWith("#")) {
677 /* most probably not a pack announcement. */
681 Optional<Network> network = getNetwork(channelMessageReceived.connection());
682 if (!network.isPresent()) {
683 /* message for unknown connection? */
687 /* parse pack information. */
688 Optional<Pack> pack = parsePack(message);
689 if (!pack.isPresent()) {
694 synchronized (networkBots) {
695 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
696 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
697 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
698 eventBus.post(new BotAdded(bot));
700 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
705 bot.addPack(pack.get());
706 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
710 * Forward all private messages to every console.
712 * @param privateMessageReceived
713 * The private message recevied event
716 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
717 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
721 * Sends a message to all console when a notice was received.
723 * @param privateNoticeReceived
724 * The notice received event
727 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
728 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
729 if (!network.isPresent()) {
733 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.reply().source().get(), network.get(), privateNoticeReceived.text())));
737 * Starts a DCC download.
739 * @param dccSendReceived
743 public void dccSendReceived(final DccSendReceived dccSendReceived) {
744 final Optional<Network> network = getNetwork(dccSendReceived.connection());
745 if (!network.isPresent()) {
749 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
750 if (packDownloads.isEmpty()) {
751 /* unknown download, ignore. */
755 /* check if it’s already downloading. */
756 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
757 if (!runningDownloads.isEmpty()) {
758 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
762 /* locate the correct download. */
763 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
766 public boolean apply(Download download) {
767 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
771 /* we did not request this download. */
772 if (requestedDownload.isEmpty()) {
776 Download download = requestedDownload.iterator().next();
778 /* check if the file already exists. */
779 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
780 if (outputFile.exists()) {
781 long existingFileSize = outputFile.length();
783 /* file already complete? */
784 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
785 /* file is apparently already complete. just move it. */
786 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
787 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
789 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
792 /* remove download. */
793 downloads.removeAll(download.pack().name());
797 /* file not complete yet, DCC resume it. */
799 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
800 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
801 } catch (IOException ioe1) {
802 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
808 /* file does not exist, start the download. */
810 OutputStream fileOutputStream = new FileOutputStream(outputFile);
811 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
812 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
813 dccReceivers.add(dccReceiver);
815 eventBus.post(new DownloadStarted(download));
816 } catch (FileNotFoundException fnfe1) {
817 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
822 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
823 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
824 if (!network.isPresent()) {
828 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
829 if (packDownloads.isEmpty()) {
830 /* unknown download, ignore. */
834 /* check if it’s already downloading. */
835 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
836 if (!runningDownloads.isEmpty()) {
837 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
841 /* locate the correct download. */
842 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
845 public boolean apply(Download download) {
846 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
850 /* we did not request this download. */
851 if (requestedDownload.isEmpty()) {
855 Download download = requestedDownload.iterator().next();
858 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
859 if (outputFile.length() != dccAcceptReceived.position()) {
860 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
861 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()));
863 downloads.removeAll(download.pack().name());
866 OutputStream outputStream = new FileOutputStream(outputFile, true);
867 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
868 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
869 dccReceivers.add(dccReceiver);
871 eventBus.post(new DownloadStarted(download));
872 } catch (FileNotFoundException fnfe1) {
877 * Closes the output stream of the download and moves the file to the final
880 * @param dccDownloadFinished
881 * The DCC download finished event
884 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
886 /* locate the correct download. */
887 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
888 if (requestedDownload.isEmpty()) {
889 /* this seems wrong. */
890 logger.warn("Download finished but could not be located.");
893 Download download = requestedDownload.iterator().next();
896 download.outputStream().close();
897 File file = new File(download.filename());
898 file.renameTo(new File(finalDirectory, download.pack().name()));
899 eventBus.post(new DownloadFinished(download));
900 dccReceivers.remove(dccDownloadFinished.dccReceiver());
901 downloads.removeAll(download.pack().name());
902 } catch (IOException ioe1) {
903 /* TODO - handle all the errors. */
904 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
909 * Closes the output stream and notifies all listeners of the failure.
911 * @param dccDownloadFailed
912 * The DCC download failed event
915 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
917 /* locate the correct download. */
918 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
919 if (requestedDownload.isEmpty()) {
920 /* this seems wrong. */
921 logger.warn("Download finished but could not be located.");
924 Download download = requestedDownload.iterator().next();
927 Closeables.close(download.outputStream(), true);
928 eventBus.post(new DownloadFailed(download));
929 dccReceivers.remove(dccDownloadFailed.dccReceiver());
930 downloads.removeAll(download.pack().name());
931 } catch (IOException ioe1) {
932 /* swallow silently. */
937 public void replyReceived(ReplyReceived replyReceived) {
938 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
946 * Returns the download of the given pack from the given bot.
949 * The pack being downloaded
951 * The bot the pack is being downloaded from
952 * @return The download, or {@link Optional#absent()} if the download could not
955 private Optional<Download> getDownload(Pack pack, Bot bot) {
956 if (!downloads.containsKey(pack.name())) {
957 return Optional.absent();
959 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
960 if (download.bot().equals(bot)) {
961 return Optional.of(download);
964 return Optional.absent();
968 * Searches all current connections for the given connection, returning the
969 * associated network.
972 * The connection to get the network for
973 * @return The network belonging to the connection, or {@link
976 private Optional<Network> getNetwork(Connection connection) {
977 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
978 if (networkConnectionEntry.getValue().equals(connection)) {
979 return Optional.of(networkConnectionEntry.getKey());
982 return Optional.absent();
986 * Returns the configured channel for the given network and name.
989 * The network the channel is located on
991 * The name of the channel
992 * @return The configured channel, or {@link Optional#absent()} if no
993 * configured channel matching the given network and name was found
995 public Optional<Channel> getChannel(Network network, String channelName) {
996 for (Channel channel : channels) {
997 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
998 return Optional.of(channel);
1001 return Optional.absent();
1005 * Returns the extra channel for the given network and name.
1008 * The network the channel is located on
1009 * @param channelName
1010 * The name of the channel
1011 * @return The extra channel, or {@link Optional#absent()} if no extra channel
1012 * matching the given network and name was found
1014 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1015 for (Channel channel : extraChannels) {
1016 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1017 return Optional.of(channel);
1020 return Optional.absent();
1024 * Parses {@link Pack} information from the given message.
1027 * The message to parse pack information from
1028 * @return The parsed pack, or {@link Optional#absent()} if the message could
1029 * not be parsed into a pack
1031 private Optional<Pack> parsePack(String message) {
1032 int squareOpen = message.indexOf('[');
1033 int squareClose = message.indexOf(']', squareOpen);
1034 if ((squareOpen == -1) && (squareClose == -1)) {
1035 return Optional.absent();
1037 String packSize = message.substring(squareOpen + 1, squareClose);
1038 String packName = message.substring(message.lastIndexOf(' ') + 1);
1039 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1040 return Optional.of(new Pack(packIndex, packSize, packName));