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.ConnectionBuilder;
43 import net.pterodactylus.irc.DccReceiver;
44 import net.pterodactylus.irc.event.ChannelJoined;
45 import net.pterodactylus.irc.event.ChannelLeft;
46 import net.pterodactylus.irc.event.ChannelMessageReceived;
47 import net.pterodactylus.irc.event.ChannelNotJoined;
48 import net.pterodactylus.irc.event.ClientQuit;
49 import net.pterodactylus.irc.event.ConnectionClosed;
50 import net.pterodactylus.irc.event.ConnectionEstablished;
51 import net.pterodactylus.irc.event.ConnectionFailed;
52 import net.pterodactylus.irc.event.DccAcceptReceived;
53 import net.pterodactylus.irc.event.DccDownloadFailed;
54 import net.pterodactylus.irc.event.DccDownloadFinished;
55 import net.pterodactylus.irc.event.DccSendReceived;
56 import net.pterodactylus.irc.event.KickedFromChannel;
57 import net.pterodactylus.irc.event.NicknameChanged;
58 import net.pterodactylus.irc.event.PrivateMessageReceived;
59 import net.pterodactylus.irc.event.PrivateNoticeReceived;
60 import net.pterodactylus.irc.event.ReplyReceived;
61 import net.pterodactylus.irc.util.RandomNickname;
62 import net.pterodactylus.xdcc.core.event.BotAdded;
63 import net.pterodactylus.xdcc.core.event.CoreStarted;
64 import net.pterodactylus.xdcc.core.event.DownloadFailed;
65 import net.pterodactylus.xdcc.core.event.DownloadFinished;
66 import net.pterodactylus.xdcc.core.event.DownloadStarted;
67 import net.pterodactylus.xdcc.core.event.GenericError;
68 import net.pterodactylus.xdcc.core.event.GenericMessage;
69 import net.pterodactylus.xdcc.core.event.MessageReceived;
70 import net.pterodactylus.xdcc.data.Bot;
71 import net.pterodactylus.xdcc.data.Channel;
72 import net.pterodactylus.xdcc.data.ConnectedNetwork;
73 import net.pterodactylus.xdcc.data.Download;
74 import net.pterodactylus.xdcc.data.Network;
75 import net.pterodactylus.xdcc.data.Pack;
76 import net.pterodactylus.xdcc.data.Server;
78 import com.google.common.base.Optional;
79 import com.google.common.base.Predicate;
80 import com.google.common.collect.FluentIterable;
81 import com.google.common.collect.HashBasedTable;
82 import com.google.common.collect.HashMultimap;
83 import com.google.common.collect.ImmutableList;
84 import com.google.common.collect.ImmutableSet;
85 import com.google.common.collect.Lists;
86 import com.google.common.collect.Maps;
87 import com.google.common.collect.Multimap;
88 import com.google.common.collect.Sets;
89 import com.google.common.collect.Table;
90 import com.google.common.eventbus.EventBus;
91 import com.google.common.eventbus.Subscribe;
92 import com.google.common.io.Closeables;
93 import com.google.common.util.concurrent.AbstractExecutionThreadService;
94 import com.google.inject.Inject;
95 import org.apache.log4j.Logger;
98 * The core of XDCC Downloader.
100 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
102 public class Core extends AbstractExecutionThreadService {
105 private static final Logger logger = Logger.getLogger(Core.class.getName());
107 /** The event bus. */
108 private final EventBus eventBus;
109 private final ChannelBanManager channelBanManager =
110 new ChannelBanManager();
112 /** The temporary directory to download files to. */
113 private final String temporaryDirectory;
115 /** The directory to move finished downloads to. */
116 private final String finalDirectory;
118 /** The channels that should be monitored. */
119 private final Collection<Channel> channels = Sets.newHashSet();
121 /** The channels that are currentlymonitored. */
122 private final Collection<Channel> joinedChannels = Sets.newHashSet();
124 /** The channels that are joined but not configured. */
125 private final Collection<Channel> extraChannels = Sets.newHashSet();
127 /** The current network connections. */
128 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
130 /** The currently known bots. */
131 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
133 /** The current downloads. */
134 private final Multimap<String, Download> downloads = HashMultimap.create();
136 /** The current DCC receivers. */
137 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
140 * Creates a new core.
144 * @param temporaryDirectory
145 * The directory to download files to
146 * @param finalDirectory
147 * The directory to move finished files to
150 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
151 this.eventBus = eventBus;
152 this.temporaryDirectory = temporaryDirectory;
153 this.finalDirectory = finalDirectory;
161 * Returns all currently known connections.
163 * @return All currently known connections
165 public Collection<Connection> connections() {
166 return networkConnections.values();
170 * Returns all defined networks.
172 * @return All defined networks
174 public Collection<Network> networks() {
175 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
179 * Returns all connected networks.
181 * @return All connected networks
183 public Collection<ConnectedNetwork> connectedNetworks() {
184 return networkConnections.entrySet().stream().map((entry) -> {
185 Network network = entry.getKey();
186 Collection<Bot> bots = networkBots.row(network).values();
187 int packCount = bots.stream().mapToInt((bot) -> bot.packs().size()).reduce((a, b) -> a + b).orElse(0);
188 return new ConnectedNetwork(network, entry.getValue().hostname(),
189 entry.getValue().port(), entry.getValue().nickname(),
191 .filter((channel) -> channel.network()
194 .collect(Collectors.<String>toList()),
195 extraChannels.stream()
196 .filter((channel) -> channel.network()
199 .collect(Collectors.<String>toList()),
200 bots.size(), packCount);
201 }).collect(Collectors.<ConnectedNetwork>toList());
205 * Returns all configured channels. Due to various circumstances, configured
206 * channels might not actually be joined.
208 * @return All configured channels
210 public Collection<Channel> channels() {
211 return ImmutableSet.copyOf(channels);
215 * Returns all currently joined channels.
217 * @return All currently joined channels
219 public Collection<Channel> joinedChannels() {
220 return ImmutableSet.copyOf(joinedChannels);
224 * Returns all currently joined channels that are not configured.
226 * @return All currently joined but not configured channels
228 public Collection<Channel> extraChannels() {
229 return ImmutableSet.copyOf(extraChannels);
233 * Returns all currently known bots.
235 * @return All currently known bots
237 public Collection<Bot> bots() {
238 return networkBots.values();
242 * Returns all currently running downloads.
244 * @return All currently running downloads
246 public Collection<Download> downloads() {
247 return downloads.values();
255 * Adds a channel to monitor.
258 * The channel to monitor
260 public void addChannel(Channel channel) {
261 channels.add(channel);
265 * Fetches the given pack from the given bot.
268 * The bot to fetch the pack from
272 public void fetch(Bot bot, Pack pack) {
273 Connection connection = networkConnections.get(bot.network());
274 if (connection == null) {
278 /* check if we are already downloading the file? */
279 if (downloads.containsKey(pack.name())) {
280 Collection<Download> packDownloads = downloads.get(pack.name());
281 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
282 if (!runningDownloads.isEmpty()) {
283 Download download = runningDownloads.iterator().next();
284 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
287 StringBuilder bots = new StringBuilder();
288 for (Download download : packDownloads) {
289 if (bots.length() > 0) {
292 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
294 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
297 Download download = new Download(bot, pack);
298 downloads.put(pack.name(), download);
301 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
302 } catch (IOException ioe1) {
303 logger.warn("Could not send message to bot!", ioe1);
308 * Cancels the download of the given pack from the given bot.
311 * The bot the pack is being downloaded from
313 * The pack being downloaded
315 public void cancelDownload(Bot bot, Pack pack) {
316 Optional<Download> download = getDownload(pack, bot);
317 if (!download.isPresent()) {
321 /* get connection. */
322 Connection connection = networkConnections.get(bot.network());
323 if (connection == null) {
324 /* request for unknown network? */
328 /* stop the DCC receiver. */
329 if (download.get().dccReceiver() != null) {
330 download.get().dccReceiver().stop();
332 /* remove download if it hasn’t started yet. */
333 downloads.remove(pack.name(), download.get());
336 /* remove the request from the bot, too. */
338 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
339 } catch (IOException ioe1) {
340 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
345 * Closes the given connection.
348 * The connection to close
350 public void closeConnection(Connection connection) {
353 } catch (IOException ioe1) {
359 // ABSTRACTIDLESERVICE METHODS
363 protected void startUp() {
364 for (Channel channel : channels) {
365 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
366 connectNetwork(channel.network());
369 /* notify listeners. */
370 eventBus.post(new CoreStarted(this));
374 protected void run() throws Exception {
375 while (isRunning()) {
377 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
378 } catch (InterruptedException ie1) {
382 /* find channels that should be monitored but are not. */
383 for (Channel channel : channels) {
384 if (joinedChannels.contains(channel)) {
388 /* are we banned from this channel? */
389 if (channelBanManager.isBanned(channel)) {
393 connectNetwork(channel.network());
394 Connection connection = networkConnections.get(channel.network());
395 if (connection.established()) {
396 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
398 connection.joinChannel(channel.name());
399 } catch (IOException ioe1) {
400 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
408 protected void shutDown() {
416 * Starts a new connection for the given network if no such connection exists
420 * The network to connect to
422 private void connectNetwork(Network network) {
423 if (!networkConnections.containsKey(network)) {
424 /* select a random server. */
425 List<Server> servers = Lists.newArrayList(network.servers());
426 if (servers.isEmpty()) {
427 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
430 Server server = servers.get((int) (Math.random() * servers.size()));
431 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
432 connection.username(RandomNickname.get()).realName(RandomNickname.get());
433 networkConnections.put(network, connection);
439 * Removes the given connection and all its channels and bots.
442 * The connection to remove
444 private void removeConnection(Connection connection) {
445 Optional<Network> network = getNetwork(connection);
446 if (!network.isPresent()) {
449 if (!connection.established()) {
453 /* find all channels that need to be removed. */
454 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
455 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
456 Channel joinedChannel = channelIterator.next();
457 if (!joinedChannel.network().equals(network.get())) {
461 channelIterator.remove();
465 /* now remove all bots for that network. */
466 Map<String, Bot> bots = networkBots.row(network.get());
467 int botCount = bots.size();
469 for (Bot bot : bots.values()) {
470 packCount += bot.packs().size();
473 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
475 /* now remove the network. */
476 networkConnections.remove(network.get());
484 * If a connection to a network has been established, the channels associated
485 * with this network are joined.
487 * @param connectionEstablished
488 * The connection established event
491 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
493 /* get network for connection. */
494 Optional<Network> network = getNetwork(connectionEstablished.connection());
497 if (!network.isPresent()) {
498 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
502 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
504 /* join all channels on this network. */
505 for (Channel channel : channels) {
506 if (channel.network().equals(network.get())) {
508 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
509 connectionEstablished.connection().joinChannel(channel.name());
510 } catch (IOException ioe1) {
511 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
518 * Remove all data stored for a network if the connection is closed.
520 * @param connectionClosed
521 * The connection closed event
524 public void connectionClosed(ConnectionClosed connectionClosed) {
525 removeConnection(connectionClosed.connection());
529 * Remove all data stored for a network if the connection fails.
531 * @param connectionFailed
532 * The connection failed event
535 public void connectionFailed(ConnectionFailed connectionFailed) {
536 removeConnection(connectionFailed.connection());
540 * Shows a message when a channel was joined by us.
542 * @param channelJoined
543 * The channel joined event
546 public void channelJoined(ChannelJoined channelJoined) {
547 if (channelJoined.connection().isSource(channelJoined.client())) {
548 Optional<Network> network = getNetwork(channelJoined.connection());
549 if (!network.isPresent()) {
553 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
554 if (!channel.isPresent()) {
555 /* it’s an extra channel. */
556 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
557 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
561 channelBanManager.unban(channel.get());
562 joinedChannels.add(channel.get());
563 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
568 public void channelNotJoined(ChannelNotJoined channelNotJoined) {
569 Optional<Network> network = getNetwork(channelNotJoined.connection());
570 if (!network.isPresent()) {
574 Optional<Channel> channel = getChannel(network.get(), channelNotJoined.channel());
575 if (!channel.isPresent()) {
576 eventBus.post(new GenericMessage(format("Could not join %s but didn’t try to join, either.", channel.get())));
580 if (channelNotJoined.reason() == registeredNicknamesOnly) {
581 channels.remove(channel.get());
582 eventBus.post(new GenericMessage(
583 format("Not trying to join %s anymore.", channel.get())));
586 if (channelNotJoined.reason() == banned) {
587 channelBanManager.ban(channel.get());
588 eventBus.post(new GenericMessage(
589 format("Banned from %s, suspending join for a day.",
594 eventBus.post(new GenericMessage(
595 format("Could not join %s: %s", channelNotJoined.channel(),
596 channelNotJoined.reason())));
600 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
603 * The channel left event
606 public void channelLeft(ChannelLeft channelLeft) {
607 Optional<Network> network = getNetwork(channelLeft.connection());
608 if (!network.isPresent()) {
612 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
614 /* maybe it was us? */
615 if (channelLeft.connection().isSource(channelLeft.client())) {
616 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
617 if (!channel.isPresent()) {
618 /* maybe it was an extra channel? */
619 channel = getExtraChannel(network.get(), channelLeft.channel());
620 if (!channel.isPresent()) {
621 /* okay, whatever. */
625 extraChannels.remove(channel);
627 channels.remove(channel.get());
630 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
636 networkBots.remove(network.get(), channelLeft.client().nick().get());
640 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
641 Optional<Network> network = getNetwork(kickedFromChannel.connection());
642 if (!network.isPresent()) {
646 /* have we been kicked? */
647 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
648 Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
649 if (!channel.isPresent()) {
650 /* maybe it was an extra channel? */
651 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
652 if (!channel.isPresent()) {
653 /* okay, whatever. */
657 extraChannels.remove(channel);
659 channels.remove(channel.get());
661 eventBus.post(new GenericMessage(format(
662 "Kicked from %s by %s: %s",
663 kickedFromChannel.channel(),
664 kickedFromChannel.kicker(),
665 kickedFromChannel.reason().or("<unknown>")
670 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
671 return connection.nickname().equalsIgnoreCase(nickname);
675 * Removes a client (which may be a bot) from the table of known bots.
678 * The client quit event
681 public void clientQuit(ClientQuit clientQuit) {
682 Optional<Network> network = getNetwork(clientQuit.connection());
683 if (!network.isPresent()) {
687 networkBots.remove(network.get(), clientQuit.client().nick().get());
691 * If the nickname of a bit changes, remove it from the old name and store it
692 * under the new name.
694 * @param nicknameChanged
695 * The nickname changed event
698 public void nicknameChanged(NicknameChanged nicknameChanged) {
699 Optional<Network> network = getNetwork(nicknameChanged.connection());
700 if (!network.isPresent()) {
704 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
709 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
713 * If a message on a channel is received, it is parsed for pack information
714 * with is then added to a bot.
716 * @param channelMessageReceived
717 * The channel message received event
720 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
721 String message = getDefaultInstance().clean(channelMessageReceived.message());
722 if (!message.startsWith("#")) {
723 /* most probably not a pack announcement. */
727 Optional<Network> network = getNetwork(channelMessageReceived.connection());
728 if (!network.isPresent()) {
729 /* message for unknown connection? */
733 /* parse pack information. */
734 Optional<Pack> pack = parsePack(message);
735 if (!pack.isPresent()) {
740 synchronized (networkBots) {
741 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
742 bot = new Bot(network.get(), channelMessageReceived.channel(),
743 channelMessageReceived.source().nick().get());
744 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
745 eventBus.post(new BotAdded(bot));
747 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
752 bot.addPack(pack.get());
753 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
757 * Forward all private messages to every console.
759 * @param privateMessageReceived
760 * The private message recevied event
763 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
764 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
768 * Sends a message to all console when a notice was received.
770 * @param privateNoticeReceived
771 * The notice received event
774 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
775 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
776 if (!network.isPresent()) {
780 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.source(), network.get(), privateNoticeReceived.text())));
784 * Starts a DCC download.
786 * @param dccSendReceived
790 public void dccSendReceived(final DccSendReceived dccSendReceived) {
791 final Optional<Network> network = getNetwork(dccSendReceived.connection());
792 if (!network.isPresent()) {
796 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
797 if (packDownloads.isEmpty()) {
798 /* unknown download, ignore. */
802 /* check if it’s already downloading. */
803 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
804 if (!runningDownloads.isEmpty()) {
805 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
809 /* locate the correct download. */
810 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
813 public boolean apply(Download download) {
814 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
818 /* we did not request this download. */
819 if (requestedDownload.isEmpty()) {
823 Download download = requestedDownload.iterator().next();
825 /* check if the file already exists. */
826 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
827 if (outputFile.exists()) {
828 long existingFileSize = outputFile.length();
830 /* file already complete? */
831 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
832 /* file is apparently already complete. just move it. */
833 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
834 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
836 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
839 /* remove download. */
840 downloads.removeAll(download.pack().name());
844 /* file not complete yet, DCC resume it. */
846 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
847 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
848 } catch (IOException ioe1) {
849 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
855 /* file does not exist, start the download. */
857 OutputStream fileOutputStream = new FileOutputStream(outputFile);
858 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
859 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
860 dccReceivers.add(dccReceiver);
862 eventBus.post(new DownloadStarted(download));
863 } catch (FileNotFoundException fnfe1) {
864 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
869 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
870 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
871 if (!network.isPresent()) {
875 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
876 if (packDownloads.isEmpty()) {
877 /* unknown download, ignore. */
881 /* check if it’s already downloading. */
882 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
883 if (!runningDownloads.isEmpty()) {
884 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
888 /* locate the correct download. */
889 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
892 public boolean apply(Download download) {
893 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
897 /* we did not request this download. */
898 if (requestedDownload.isEmpty()) {
902 Download download = requestedDownload.iterator().next();
905 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
906 if (outputFile.length() != dccAcceptReceived.position()) {
907 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
908 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()));
910 downloads.removeAll(download.pack().name());
913 OutputStream outputStream = new FileOutputStream(outputFile, true);
914 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
915 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
916 dccReceivers.add(dccReceiver);
918 eventBus.post(new DownloadStarted(download));
919 } catch (FileNotFoundException fnfe1) {
924 * Closes the output stream of the download and moves the file to the final
927 * @param dccDownloadFinished
928 * The DCC download finished event
931 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
933 /* locate the correct download. */
934 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
935 if (requestedDownload.isEmpty()) {
936 /* this seems wrong. */
937 logger.warn("Download finished but could not be located.");
940 Download download = requestedDownload.iterator().next();
943 download.outputStream().close();
944 File file = new File(download.filename());
945 file.renameTo(new File(finalDirectory, download.pack().name()));
946 eventBus.post(new DownloadFinished(download));
947 dccReceivers.remove(dccDownloadFinished.dccReceiver());
948 downloads.removeAll(download.pack().name());
949 } catch (IOException ioe1) {
950 /* TODO - handle all the errors. */
951 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
956 * Closes the output stream and notifies all listeners of the failure.
958 * @param dccDownloadFailed
959 * The DCC download failed event
962 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
964 /* locate the correct download. */
965 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
966 if (requestedDownload.isEmpty()) {
967 /* this seems wrong. */
968 logger.warn("Download finished but could not be located.");
971 Download download = requestedDownload.iterator().next();
974 Closeables.close(download.outputStream(), true);
975 eventBus.post(new DownloadFailed(download));
976 dccReceivers.remove(dccDownloadFailed.dccReceiver());
977 downloads.removeAll(download.pack().name());
978 } catch (IOException ioe1) {
979 /* swallow silently. */
984 public void replyReceived(ReplyReceived replyReceived) {
985 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
993 * Returns the download of the given pack from the given bot.
996 * The pack being downloaded
998 * The bot the pack is being downloaded from
999 * @return The download, or {@link Optional#absent()} if the download could not
1002 private Optional<Download> getDownload(Pack pack, Bot bot) {
1003 if (!downloads.containsKey(pack.name())) {
1004 return Optional.absent();
1006 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
1007 if (download.bot().equals(bot)) {
1008 return Optional.of(download);
1011 return Optional.absent();
1015 * Searches all current connections for the given connection, returning the
1016 * associated network.
1019 * The connection to get the network for
1020 * @return The network belonging to the connection, or {@link
1021 * Optional#absent()}
1023 private Optional<Network> getNetwork(Connection connection) {
1024 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
1025 if (networkConnectionEntry.getValue().equals(connection)) {
1026 return Optional.of(networkConnectionEntry.getKey());
1029 return Optional.absent();
1033 * Returns the configured channel for the given network and name.
1036 * The network the channel is located on
1037 * @param channelName
1038 * The name of the channel
1039 * @return The configured channel, or {@link Optional#absent()} if no
1040 * configured channel matching the given network and name was found
1042 public Optional<Channel> getChannel(Network network, String channelName) {
1043 for (Channel channel : channels) {
1044 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1045 return Optional.of(channel);
1048 return Optional.absent();
1052 * Returns the extra channel for the given network and name.
1055 * The network the channel is located on
1056 * @param channelName
1057 * The name of the channel
1058 * @return The extra channel, or {@link Optional#absent()} if no extra channel
1059 * matching the given network and name was found
1061 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1062 for (Channel channel : extraChannels) {
1063 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1064 return Optional.of(channel);
1067 return Optional.absent();
1071 * Parses {@link Pack} information from the given message.
1074 * The message to parse pack information from
1075 * @return The parsed pack, or {@link Optional#absent()} if the message could
1076 * not be parsed into a pack
1078 private Optional<Pack> parsePack(String message) {
1079 int squareOpen = message.indexOf('[');
1080 int squareClose = message.indexOf(']', squareOpen);
1081 if ((squareOpen == -1) && (squareClose == -1)) {
1082 return Optional.absent();
1084 String packSize = message.substring(squareOpen + 1, squareClose);
1085 String packName = message.substring(message.lastIndexOf(' ') + 1);
1086 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1087 return Optional.of(new Pack(packIndex, packSize, packName));