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.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 ConnectionFactory connectionFactory;
110 private final ChannelBanManager channelBanManager =
111 new ChannelBanManager();
113 /** The temporary directory to download files to. */
114 private final String temporaryDirectory;
116 /** The directory to move finished downloads to. */
117 private final String finalDirectory;
119 /** The channels that should be monitored. */
120 private final Collection<Channel> channels = Sets.newHashSet();
122 /** The channels that are currentlymonitored. */
123 private final Collection<Channel> joinedChannels = Sets.newHashSet();
125 /** The channels that are joined but not configured. */
126 private final Collection<Channel> extraChannels = Sets.newHashSet();
128 /** The current network connections. */
129 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
131 /** The currently known bots. */
132 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
134 /** The current downloads. */
135 private final Multimap<String, Download> downloads = HashMultimap.create();
137 /** The current DCC receivers. */
138 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
141 * Creates a new core.
145 * @param temporaryDirectory
146 * The directory to download files to
147 * @param finalDirectory
148 * The directory to move finished files to
151 public Core(EventBus eventBus, ConnectionFactory connectionFactory, String temporaryDirectory, String finalDirectory) {
152 this.eventBus = eventBus;
153 this.connectionFactory = connectionFactory;
154 this.temporaryDirectory = temporaryDirectory;
155 this.finalDirectory = finalDirectory;
163 * Returns all currently known connections.
165 * @return All currently known connections
167 public Collection<Connection> connections() {
168 return networkConnections.values();
172 * Returns all defined networks.
174 * @return All defined networks
176 public Collection<Network> networks() {
177 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
181 * Returns all connected networks.
183 * @return All connected networks
185 public Collection<ConnectedNetwork> connectedNetworks() {
186 return networkConnections.entrySet().stream().map((entry) -> {
187 Network network = entry.getKey();
188 Collection<Bot> bots = networkBots.row(network).values();
189 int packCount = bots.stream().mapToInt((bot) -> bot.packs().size()).reduce((a, b) -> a + b).orElse(0);
190 return new ConnectedNetwork(network, entry.getValue().hostname(),
191 entry.getValue().port(), entry.getValue().nickname(),
193 .filter((channel) -> channel.network()
196 .collect(Collectors.<String>toList()),
197 extraChannels.stream()
198 .filter((channel) -> channel.network()
201 .collect(Collectors.<String>toList()),
202 bots.size(), packCount);
203 }).collect(Collectors.<ConnectedNetwork>toList());
207 * Returns all configured channels. Due to various circumstances, configured
208 * channels might not actually be joined.
210 * @return All configured channels
212 public Collection<Channel> channels() {
213 return ImmutableSet.copyOf(channels);
217 * Returns all currently joined channels.
219 * @return All currently joined channels
221 public Collection<Channel> joinedChannels() {
222 return ImmutableSet.copyOf(joinedChannels);
226 * Returns all currently joined channels that are not configured.
228 * @return All currently joined but not configured channels
230 public Collection<Channel> extraChannels() {
231 return ImmutableSet.copyOf(extraChannels);
235 * Returns all currently known bots.
237 * @return All currently known bots
239 public Collection<Bot> bots() {
240 return networkBots.values();
244 * Returns all currently running downloads.
246 * @return All currently running downloads
248 public Collection<Download> downloads() {
249 return downloads.values();
257 * Adds a channel to monitor.
260 * The channel to monitor
262 public void addChannel(Channel channel) {
263 channels.add(channel);
267 * Fetches the given pack from the given bot.
270 * The bot to fetch the pack from
274 public void fetch(Bot bot, Pack pack) {
275 Connection connection = networkConnections.get(bot.network());
276 if (connection == null) {
280 /* check if we are already downloading the file? */
281 if (downloads.containsKey(pack.name())) {
282 Collection<Download> packDownloads = downloads.get(pack.name());
283 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
284 if (!runningDownloads.isEmpty()) {
285 Download download = runningDownloads.iterator().next();
286 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
289 StringBuilder bots = new StringBuilder();
290 for (Download download : packDownloads) {
291 if (bots.length() > 0) {
294 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
296 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
299 Download download = new Download(bot, pack);
300 downloads.put(pack.name(), download);
303 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
304 } catch (IOException ioe1) {
305 logger.warn("Could not send message to bot!", ioe1);
310 * Cancels the download of the given pack from the given bot.
313 * The bot the pack is being downloaded from
315 * The pack being downloaded
317 public void cancelDownload(Bot bot, Pack pack) {
318 Optional<Download> download = getDownload(pack, bot);
319 if (!download.isPresent()) {
323 /* get connection. */
324 Connection connection = networkConnections.get(bot.network());
325 if (connection == null) {
326 /* request for unknown network? */
330 /* stop the DCC receiver. */
331 if (download.get().dccReceiver() != null) {
332 download.get().dccReceiver().stop();
334 /* remove download if it hasn’t started yet. */
335 downloads.remove(pack.name(), download.get());
338 /* remove the request from the bot, too. */
340 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
341 } catch (IOException ioe1) {
342 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
347 * Closes the given connection.
350 * The connection to close
352 public void closeConnection(Connection connection) {
355 } catch (IOException ioe1) {
361 // ABSTRACTIDLESERVICE METHODS
365 protected void startUp() {
366 for (Channel channel : channels) {
367 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
368 connectNetwork(channel.network());
371 /* notify listeners. */
372 eventBus.post(new CoreStarted(this));
376 protected void run() throws Exception {
377 while (isRunning()) {
379 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
380 } catch (InterruptedException ie1) {
384 /* find channels that should be monitored but are not. */
385 for (Channel channel : channels) {
386 if (joinedChannels.contains(channel)) {
390 /* are we banned from this channel? */
391 if (channelBanManager.isBanned(channel)) {
395 connectNetwork(channel.network());
396 Connection connection = networkConnections.get(channel.network());
397 if (connection.established()) {
398 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
400 connection.joinChannel(channel.name());
401 } catch (IOException ioe1) {
402 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
410 protected void shutDown() {
418 * Starts a new connection for the given network if no such connection exists
422 * The network to connect to
424 private void connectNetwork(Network network) {
425 if (!networkConnections.containsKey(network)) {
426 /* select a random server. */
427 List<Server> servers = Lists.newArrayList(network.servers());
428 if (servers.isEmpty()) {
429 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
432 Server server = servers.get((int) (Math.random() * servers.size()));
433 Connection connection = connectionFactory.createConnection(server.hostname(), server.unencryptedPorts().iterator().next());
434 connection.username(RandomNickname.get()).realName(RandomNickname.get());
435 networkConnections.put(network, connection);
441 * Removes the given connection and all its channels and bots.
444 * The connection to remove
446 private void removeConnection(Connection connection) {
447 Optional<Network> network = getNetwork(connection);
448 if (!network.isPresent()) {
451 if (!connection.established()) {
455 /* find all channels that need to be removed. */
456 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
457 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
458 Channel joinedChannel = channelIterator.next();
459 if (!joinedChannel.network().equals(network.get())) {
463 channelIterator.remove();
467 /* now remove all bots for that network. */
468 Map<String, Bot> bots = networkBots.row(network.get());
469 int botCount = bots.size();
471 for (Bot bot : bots.values()) {
472 packCount += bot.packs().size();
475 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
477 /* now remove the network. */
478 networkConnections.remove(network.get());
486 * If a connection to a network has been established, the channels associated
487 * with this network are joined.
489 * @param connectionEstablished
490 * The connection established event
493 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
495 /* get network for connection. */
496 Optional<Network> network = getNetwork(connectionEstablished.connection());
499 if (!network.isPresent()) {
500 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
504 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
506 /* join all channels on this network. */
507 for (Channel channel : channels) {
508 if (channel.network().equals(network.get())) {
510 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
511 connectionEstablished.connection().joinChannel(channel.name());
512 } catch (IOException ioe1) {
513 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
520 * Remove all data stored for a network if the connection is closed.
522 * @param connectionClosed
523 * The connection closed event
526 public void connectionClosed(ConnectionClosed connectionClosed) {
527 removeConnection(connectionClosed.connection());
531 * Remove all data stored for a network if the connection fails.
533 * @param connectionFailed
534 * The connection failed event
537 public void connectionFailed(ConnectionFailed connectionFailed) {
538 removeConnection(connectionFailed.connection());
542 * Shows a message when a channel was joined by us.
544 * @param channelJoined
545 * The channel joined event
548 public void channelJoined(ChannelJoined channelJoined) {
549 if (channelJoined.connection().isSource(channelJoined.client())) {
550 Optional<Network> network = getNetwork(channelJoined.connection());
551 if (!network.isPresent()) {
555 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
556 if (!channel.isPresent()) {
557 /* it’s an extra channel. */
558 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
559 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
563 channelBanManager.unban(channel.get());
564 joinedChannels.add(channel.get());
565 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
570 public void channelNotJoined(ChannelNotJoined channelNotJoined) {
571 Optional<Network> network = getNetwork(channelNotJoined.connection());
572 if (!network.isPresent()) {
576 Optional<Channel> channel = getChannel(network.get(), channelNotJoined.channel());
577 if (!channel.isPresent()) {
578 eventBus.post(new GenericMessage(format("Could not join %s but didn’t try to join, either.", channel.get())));
582 /* remove all bots for this channel, we might have been kicked. */
583 Collection<Bot> botsToRemove = networkBots.row(network.get())
585 .filter(bot -> bot.channel()
586 .equalsIgnoreCase(channel.get().name()))
587 .collect(Collectors.toSet());
588 botsToRemove.stream()
589 .forEach(bot -> networkBots.row(network.get())
590 .remove(bot.name()));
592 if (channelNotJoined.reason() == registeredNicknamesOnly) {
593 channels.remove(channel.get());
594 eventBus.post(new GenericMessage(
595 format("Not trying to join %s anymore.", channel.get())));
598 if (channelNotJoined.reason() == banned) {
599 channelBanManager.ban(channel.get());
600 eventBus.post(new GenericMessage(
601 format("Banned from %s, suspending join for a day.",
606 eventBus.post(new GenericMessage(
607 format("Could not join %s: %s", channelNotJoined.channel(),
608 channelNotJoined.reason())));
612 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
615 * The channel left event
618 public void channelLeft(ChannelLeft channelLeft) {
619 Optional<Network> network = getNetwork(channelLeft.connection());
620 if (!network.isPresent()) {
624 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
626 /* maybe it was us? */
627 if (channelLeft.connection().isSource(channelLeft.client())) {
628 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
629 if (!channel.isPresent()) {
630 /* maybe it was an extra channel? */
631 channel = getExtraChannel(network.get(), channelLeft.channel());
632 if (!channel.isPresent()) {
633 /* okay, whatever. */
637 extraChannels.remove(channel);
639 channels.remove(channel.get());
642 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
648 networkBots.remove(network.get(), channelLeft.client().nick().get());
652 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
653 Optional<Network> network = getNetwork(kickedFromChannel.connection());
654 if (!network.isPresent()) {
658 /* have we been kicked? */
659 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
660 Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
661 if (!channel.isPresent()) {
662 /* maybe it was an extra channel? */
663 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
664 if (!channel.isPresent()) {
665 /* okay, whatever. */
669 extraChannels.remove(channel);
671 channels.remove(channel.get());
673 eventBus.post(new GenericMessage(format(
674 "Kicked from %s by %s: %s",
675 kickedFromChannel.channel(),
676 kickedFromChannel.kicker(),
677 kickedFromChannel.reason().or("<unknown>")
682 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
683 return connection.nickname().equalsIgnoreCase(nickname);
687 * Removes a client (which may be a bot) from the table of known bots.
690 * The client quit event
693 public void clientQuit(ClientQuit clientQuit) {
694 Optional<Network> network = getNetwork(clientQuit.connection());
695 if (!network.isPresent()) {
699 networkBots.remove(network.get(), clientQuit.client().nick().get());
703 * If the nickname of a bit changes, remove it from the old name and store it
704 * under the new name.
706 * @param nicknameChanged
707 * The nickname changed event
710 public void nicknameChanged(NicknameChanged nicknameChanged) {
711 Optional<Network> network = getNetwork(nicknameChanged.connection());
712 if (!network.isPresent()) {
716 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
721 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
725 * If a message on a channel is received, it is parsed for pack information
726 * with is then added to a bot.
728 * @param channelMessageReceived
729 * The channel message received event
732 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
733 String message = getDefaultInstance().clean(channelMessageReceived.message());
734 if (!message.startsWith("#")) {
735 /* most probably not a pack announcement. */
739 Optional<Network> network = getNetwork(channelMessageReceived.connection());
740 if (!network.isPresent()) {
741 /* message for unknown connection? */
745 /* parse pack information. */
746 Optional<Pack> pack = parsePack(message);
747 if (!pack.isPresent()) {
752 synchronized (networkBots) {
753 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
754 bot = new Bot(network.get(), channelMessageReceived.channel(),
755 channelMessageReceived.source().nick().get());
756 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
757 eventBus.post(new BotAdded(bot));
759 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
764 bot.addPack(pack.get());
765 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
769 * Forward all private messages to every console.
771 * @param privateMessageReceived
772 * The private message recevied event
775 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
776 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
780 * Sends a message to all console when a notice was received.
782 * @param privateNoticeReceived
783 * The notice received event
786 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
787 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
788 if (!network.isPresent()) {
792 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.source(), network.get(), privateNoticeReceived.text())));
796 * Starts a DCC download.
798 * @param dccSendReceived
802 public void dccSendReceived(final DccSendReceived dccSendReceived) {
803 final Optional<Network> network = getNetwork(dccSendReceived.connection());
804 if (!network.isPresent()) {
808 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
809 if (packDownloads.isEmpty()) {
810 /* unknown download, ignore. */
814 /* check if it’s already downloading. */
815 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
816 if (!runningDownloads.isEmpty()) {
817 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
821 /* locate the correct download. */
822 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
825 public boolean apply(Download download) {
826 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
830 /* we did not request this download. */
831 if (requestedDownload.isEmpty()) {
835 Download download = requestedDownload.iterator().next();
837 /* check if the file already exists. */
838 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
839 if (outputFile.exists()) {
840 long existingFileSize = outputFile.length();
842 /* file already complete? */
843 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
844 /* file is apparently already complete. just move it. */
845 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
846 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
848 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
851 /* remove download. */
852 downloads.removeAll(download.pack().name());
856 /* file not complete yet, DCC resume it. */
858 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
859 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
860 } catch (IOException ioe1) {
861 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
867 /* file does not exist, start the download. */
869 OutputStream fileOutputStream = new FileOutputStream(outputFile);
870 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
871 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
872 dccReceivers.add(dccReceiver);
874 eventBus.post(new DownloadStarted(download));
875 } catch (FileNotFoundException fnfe1) {
876 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
881 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
882 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
883 if (!network.isPresent()) {
887 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
888 if (packDownloads.isEmpty()) {
889 /* unknown download, ignore. */
893 /* check if it’s already downloading. */
894 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
895 if (!runningDownloads.isEmpty()) {
896 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
900 /* locate the correct download. */
901 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
904 public boolean apply(Download download) {
905 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
909 /* we did not request this download. */
910 if (requestedDownload.isEmpty()) {
914 Download download = requestedDownload.iterator().next();
917 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
918 if (outputFile.length() != dccAcceptReceived.position()) {
919 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
920 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()));
922 downloads.removeAll(download.pack().name());
925 OutputStream outputStream = new FileOutputStream(outputFile, true);
926 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
927 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
928 dccReceivers.add(dccReceiver);
930 eventBus.post(new DownloadStarted(download));
931 } catch (FileNotFoundException fnfe1) {
936 * Closes the output stream of the download and moves the file to the final
939 * @param dccDownloadFinished
940 * The DCC download finished event
943 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
945 /* locate the correct download. */
946 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
947 if (requestedDownload.isEmpty()) {
948 /* this seems wrong. */
949 logger.warn("Download finished but could not be located.");
952 Download download = requestedDownload.iterator().next();
955 download.outputStream().close();
956 File file = new File(download.filename());
957 file.renameTo(new File(finalDirectory, download.pack().name()));
958 eventBus.post(new DownloadFinished(download));
959 dccReceivers.remove(dccDownloadFinished.dccReceiver());
960 downloads.removeAll(download.pack().name());
961 } catch (IOException ioe1) {
962 /* TODO - handle all the errors. */
963 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
968 * Closes the output stream and notifies all listeners of the failure.
970 * @param dccDownloadFailed
971 * The DCC download failed event
974 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
976 /* locate the correct download. */
977 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
978 if (requestedDownload.isEmpty()) {
979 /* this seems wrong. */
980 logger.warn("Download finished but could not be located.");
983 Download download = requestedDownload.iterator().next();
986 Closeables.close(download.outputStream(), true);
987 eventBus.post(new DownloadFailed(download));
988 dccReceivers.remove(dccDownloadFailed.dccReceiver());
989 downloads.removeAll(download.pack().name());
990 } catch (IOException ioe1) {
991 /* swallow silently. */
996 public void replyReceived(ReplyReceived replyReceived) {
997 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
1005 * Returns the download of the given pack from the given bot.
1008 * The pack being downloaded
1010 * The bot the pack is being downloaded from
1011 * @return The download, or {@link Optional#absent()} if the download could not
1014 private Optional<Download> getDownload(Pack pack, Bot bot) {
1015 if (!downloads.containsKey(pack.name())) {
1016 return Optional.absent();
1018 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
1019 if (download.bot().equals(bot)) {
1020 return Optional.of(download);
1023 return Optional.absent();
1027 * Searches all current connections for the given connection, returning the
1028 * associated network.
1031 * The connection to get the network for
1032 * @return The network belonging to the connection, or {@link
1033 * Optional#absent()}
1035 private Optional<Network> getNetwork(Connection connection) {
1036 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
1037 if (networkConnectionEntry.getValue().equals(connection)) {
1038 return Optional.of(networkConnectionEntry.getKey());
1041 return Optional.absent();
1045 * Returns the configured channel for the given network and name.
1048 * The network the channel is located on
1049 * @param channelName
1050 * The name of the channel
1051 * @return The configured channel, or {@link Optional#absent()} if no
1052 * configured channel matching the given network and name was found
1054 public Optional<Channel> getChannel(Network network, String channelName) {
1055 for (Channel channel : channels) {
1056 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1057 return Optional.of(channel);
1060 return Optional.absent();
1064 * Returns the extra channel for the given network and name.
1067 * The network the channel is located on
1068 * @param channelName
1069 * The name of the channel
1070 * @return The extra channel, or {@link Optional#absent()} if no extra channel
1071 * matching the given network and name was found
1073 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1074 for (Channel channel : extraChannels) {
1075 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1076 return Optional.of(channel);
1079 return Optional.absent();
1083 * Parses {@link Pack} information from the given message.
1086 * The message to parse pack information from
1087 * @return The parsed pack, or {@link Optional#absent()} if the message could
1088 * not be parsed into a pack
1090 private Optional<Pack> parsePack(String message) {
1091 int squareOpen = message.indexOf('[');
1092 int squareClose = message.indexOf(']', squareOpen);
1093 if ((squareOpen == -1) && (squareClose == -1)) {
1094 return Optional.absent();
1096 String packSize = message.substring(squareOpen + 1, squareClose);
1097 String packName = message.substring(message.lastIndexOf(' ') + 1);
1098 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1099 return Optional.of(new Pack(packIndex, packSize, packName));