2 * XdccDownloader - Core.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.xdcc.core;
20 import static java.lang.String.format;
21 import static net.pterodactylus.irc.event.ChannelNotJoined.Reason.banned;
22 import static net.pterodactylus.irc.event.ChannelNotJoined.Reason.registeredNicknamesOnly;
23 import static net.pterodactylus.irc.util.MessageCleaner.getDefaultInstance;
24 import static net.pterodactylus.xdcc.data.Channel.TO_NETWORK;
25 import static net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
28 import java.io.FileNotFoundException;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.io.OutputStream;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.Iterator;
35 import java.util.List;
37 import java.util.Map.Entry;
38 import java.util.concurrent.TimeUnit;
39 import java.util.stream.Collectors;
41 import net.pterodactylus.irc.Connection;
42 import net.pterodactylus.irc.ConnectionFactory;
43 import net.pterodactylus.irc.DccReceiver;
44 import net.pterodactylus.irc.DefaultConnection;
45 import net.pterodactylus.irc.event.ChannelJoined;
46 import net.pterodactylus.irc.event.ChannelLeft;
47 import net.pterodactylus.irc.event.ChannelMessageReceived;
48 import net.pterodactylus.irc.event.ChannelNotJoined;
49 import net.pterodactylus.irc.event.ClientQuit;
50 import net.pterodactylus.irc.event.ConnectionClosed;
51 import net.pterodactylus.irc.event.ConnectionEstablished;
52 import net.pterodactylus.irc.event.ConnectionFailed;
53 import net.pterodactylus.irc.event.DccAcceptReceived;
54 import net.pterodactylus.irc.event.DccDownloadFailed;
55 import net.pterodactylus.irc.event.DccDownloadFinished;
56 import net.pterodactylus.irc.event.DccSendReceived;
57 import net.pterodactylus.irc.event.KickedFromChannel;
58 import net.pterodactylus.irc.event.NicknameChanged;
59 import net.pterodactylus.irc.event.PrivateMessageReceived;
60 import net.pterodactylus.irc.event.PrivateNoticeReceived;
61 import net.pterodactylus.irc.event.ReplyReceived;
62 import net.pterodactylus.irc.util.RandomNickname;
63 import net.pterodactylus.xdcc.core.event.BotAdded;
64 import net.pterodactylus.xdcc.core.event.CoreStarted;
65 import net.pterodactylus.xdcc.core.event.DownloadFailed;
66 import net.pterodactylus.xdcc.core.event.DownloadFinished;
67 import net.pterodactylus.xdcc.core.event.DownloadStarted;
68 import net.pterodactylus.xdcc.core.event.GenericError;
69 import net.pterodactylus.xdcc.core.event.GenericMessage;
70 import net.pterodactylus.xdcc.core.event.MessageReceived;
71 import net.pterodactylus.xdcc.data.Bot;
72 import net.pterodactylus.xdcc.data.Channel;
73 import net.pterodactylus.xdcc.data.ConnectedNetwork;
74 import net.pterodactylus.xdcc.data.Download;
75 import net.pterodactylus.xdcc.data.Network;
76 import net.pterodactylus.xdcc.data.Pack;
77 import net.pterodactylus.xdcc.data.Server;
79 import com.google.common.base.Optional;
80 import com.google.common.base.Predicate;
81 import com.google.common.collect.FluentIterable;
82 import com.google.common.collect.HashBasedTable;
83 import com.google.common.collect.HashMultimap;
84 import com.google.common.collect.ImmutableList;
85 import com.google.common.collect.ImmutableSet;
86 import com.google.common.collect.Lists;
87 import com.google.common.collect.Maps;
88 import com.google.common.collect.Multimap;
89 import com.google.common.collect.Sets;
90 import com.google.common.collect.Table;
91 import com.google.common.eventbus.EventBus;
92 import com.google.common.eventbus.Subscribe;
93 import com.google.common.io.Closeables;
94 import com.google.common.util.concurrent.AbstractExecutionThreadService;
95 import com.google.inject.Inject;
96 import org.apache.log4j.Logger;
99 * The core of XDCC Downloader.
101 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
103 public class Core extends AbstractExecutionThreadService {
106 private static final Logger logger = Logger.getLogger(Core.class.getName());
108 private final Object syncObject = new Object();
109 /** The event bus. */
110 private final EventBus eventBus;
111 private final ConnectionFactory connectionFactory;
112 private final ChannelBanManager channelBanManager =
113 new ChannelBanManager();
115 /** The temporary directory to download files to. */
116 private final String temporaryDirectory;
118 /** The directory to move finished downloads to. */
119 private final String finalDirectory;
121 /** The channels that should be monitored. */
122 private final Collection<Channel> channels = Sets.newHashSet();
124 /** The channels that are currentlymonitored. */
125 private final Collection<Channel> joinedChannels = Sets.newHashSet();
127 /** The channels that are joined but not configured. */
128 private final Collection<Channel> extraChannels = Sets.newHashSet();
130 /** The current network connections. */
131 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
133 /** The currently known bots. */
134 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
136 /** The current downloads. */
137 private final Multimap<String, Download> downloads = HashMultimap.create();
139 /** The current DCC receivers. */
140 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
143 * Creates a new core.
147 * @param temporaryDirectory
148 * The directory to download files to
149 * @param finalDirectory
150 * The directory to move finished files to
153 public Core(EventBus eventBus, ConnectionFactory connectionFactory, String temporaryDirectory, String finalDirectory) {
154 this.eventBus = eventBus;
155 this.connectionFactory = connectionFactory;
156 this.temporaryDirectory = temporaryDirectory;
157 this.finalDirectory = finalDirectory;
165 * Returns all currently known connections.
167 * @return All currently known connections
169 public Collection<Connection> connections() {
170 return networkConnections.values();
174 * Returns all defined networks.
176 * @return All defined networks
178 public Collection<Network> networks() {
179 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
183 * Returns all connected networks.
185 * @return All connected networks
187 public Collection<ConnectedNetwork> connectedNetworks() {
188 return networkConnections.entrySet().stream().map((entry) -> {
189 Network network = entry.getKey();
190 Collection<Bot> bots = networkBots.row(network).values();
191 int packCount = bots.stream().mapToInt((bot) -> bot.packs().size()).reduce((a, b) -> a + b).orElse(0);
192 return new ConnectedNetwork(network, entry.getValue().hostname(),
193 entry.getValue().port(), entry.getValue().nickname(),
195 .filter((channel) -> channel.network()
198 .collect(Collectors.<String>toList()),
199 extraChannels.stream()
200 .filter((channel) -> channel.network()
203 .collect(Collectors.<String>toList()),
204 bots.size(), packCount);
205 }).collect(Collectors.<ConnectedNetwork>toList());
209 * Returns all configured channels. Due to various circumstances, configured
210 * channels might not actually be joined.
212 * @return All configured channels
214 public Collection<Channel> channels() {
215 return ImmutableSet.copyOf(channels);
219 * Returns all currently joined channels.
221 * @return All currently joined channels
223 public Collection<Channel> joinedChannels() {
224 return ImmutableSet.copyOf(joinedChannels);
228 * Returns all currently joined channels that are not configured.
230 * @return All currently joined but not configured channels
232 public Collection<Channel> extraChannels() {
233 return ImmutableSet.copyOf(extraChannels);
237 * Returns all currently known bots.
239 * @return All currently known bots
241 public Collection<Bot> bots() {
242 return networkBots.values();
246 * Returns all currently running downloads.
248 * @return All currently running downloads
250 public Collection<Download> downloads() {
251 return downloads.values();
259 * Adds a channel to monitor.
262 * The channel to monitor
264 public void addChannel(Channel channel) {
265 channels.add(channel);
269 * Fetches the given pack from the given bot.
272 * The bot to fetch the pack from
276 public void fetch(Bot bot, Pack pack) {
277 Connection connection = networkConnections.get(bot.network());
278 if (connection == null) {
282 /* check if we are already downloading the file? */
283 if (downloads.containsKey(pack.name())) {
284 Collection<Download> packDownloads = downloads.get(pack.name());
285 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
286 if (!runningDownloads.isEmpty()) {
287 Download download = runningDownloads.iterator().next();
288 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
291 StringBuilder bots = new StringBuilder();
292 for (Download download : packDownloads) {
293 if (bots.length() > 0) {
296 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
298 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
301 Download download = new Download(bot, pack);
302 downloads.put(pack.name(), download);
305 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
306 } catch (IOException ioe1) {
307 logger.warn("Could not send message to bot!", ioe1);
312 * Cancels the download of the given pack from the given bot.
315 * The bot the pack is being downloaded from
317 * The pack being downloaded
319 public void cancelDownload(Bot bot, Pack pack) {
320 Optional<Download> download = getDownload(pack, bot);
321 if (!download.isPresent()) {
325 /* get connection. */
326 Connection connection = networkConnections.get(bot.network());
327 if (connection == null) {
328 /* request for unknown network? */
332 /* stop the DCC receiver. */
333 if (download.get().dccReceiver() != null) {
334 download.get().dccReceiver().stop();
336 /* remove download if it hasn’t started yet. */
337 downloads.remove(pack.name(), download.get());
340 /* remove the request from the bot, too. */
342 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
343 } catch (IOException ioe1) {
344 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
349 * Closes the given connection.
352 * The connection to close
354 public void closeConnection(Connection connection) {
357 } catch (IOException ioe1) {
363 // ABSTRACTIDLESERVICE METHODS
367 protected void startUp() {
368 for (Channel channel : channels) {
369 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
370 connectNetwork(channel.network());
373 /* notify listeners. */
374 eventBus.post(new CoreStarted(this));
378 protected void run() throws Exception {
379 while (isRunning()) {
380 synchronized (syncObject) {
382 syncObject.wait(TimeUnit.MINUTES.toMillis(1));
383 } catch (InterruptedException ie1) {
388 /* find channels that should be monitored but are not. */
389 for (Channel channel : channels) {
390 if (joinedChannels.contains(channel)) {
394 /* are we banned from this channel? */
395 if (channelBanManager.isBanned(channel)) {
399 connectNetwork(channel.network());
400 Connection connection = networkConnections.get(channel.network());
401 if (connection.established()) {
402 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
404 connection.joinChannel(channel.name());
405 } catch (IOException ioe1) {
406 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
414 protected void shutDown() {
415 synchronized (syncObject) {
416 syncObject.notifyAll();
425 * Starts a new connection for the given network if no such connection exists
429 * The network to connect to
431 private void connectNetwork(Network network) {
432 if (!networkConnections.containsKey(network)) {
433 /* select a random server. */
434 List<Server> servers = Lists.newArrayList(network.servers());
435 if (servers.isEmpty()) {
436 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
439 Server server = servers.get((int) (Math.random() * servers.size()));
440 Connection connection = connectionFactory.createConnection(server.hostname(),
441 server.unencryptedPorts().iterator().next());
442 connection.username(RandomNickname.get()).realName(RandomNickname.get());
443 networkConnections.put(network, connection);
449 * Removes the given connection and all its channels and bots.
452 * The connection to remove
454 private void removeConnection(Connection connection) {
455 Optional<Network> network = getNetwork(connection);
456 if (!network.isPresent()) {
459 if (!connection.established()) {
463 /* find all channels that need to be removed. */
464 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
465 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
466 Channel joinedChannel = channelIterator.next();
467 if (!joinedChannel.network().equals(network.get())) {
471 channelIterator.remove();
475 /* now remove all bots for that network. */
476 Map<String, Bot> bots = networkBots.row(network.get());
477 int botCount = bots.size();
479 for (Bot bot : bots.values()) {
480 packCount += bot.packs().size();
483 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
485 /* now remove the network. */
486 networkConnections.remove(network.get());
494 * If a connection to a network has been established, the channels associated
495 * with this network are joined.
497 * @param connectionEstablished
498 * The connection established event
501 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
503 /* get network for connection. */
504 Optional<Network> network = getNetwork(connectionEstablished.connection());
507 if (!network.isPresent()) {
508 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
512 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
514 /* join all channels on this network. */
515 for (Channel channel : channels) {
516 if (channel.network().equals(network.get())) {
518 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
519 connectionEstablished.connection().joinChannel(channel.name());
520 } catch (IOException ioe1) {
521 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
528 * Remove all data stored for a network if the connection is closed.
530 * @param connectionClosed
531 * The connection closed event
534 public void connectionClosed(ConnectionClosed connectionClosed) {
535 removeConnection(connectionClosed.connection());
539 * Remove all data stored for a network if the connection fails.
541 * @param connectionFailed
542 * The connection failed event
545 public void connectionFailed(ConnectionFailed connectionFailed) {
546 removeConnection(connectionFailed.connection());
550 * Shows a message when a channel was joined by us.
552 * @param channelJoined
553 * The channel joined event
556 public void channelJoined(ChannelJoined channelJoined) {
557 if (channelJoined.connection().isSource(channelJoined.client())) {
558 Optional<Network> network = getNetwork(channelJoined.connection());
559 if (!network.isPresent()) {
563 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
564 if (!channel.isPresent()) {
565 /* it’s an extra channel. */
566 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
567 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
571 channelBanManager.unban(channel.get());
572 joinedChannels.add(channel.get());
573 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
578 public void channelNotJoined(ChannelNotJoined channelNotJoined) {
579 Optional<Network> network = getNetwork(channelNotJoined.connection());
580 if (!network.isPresent()) {
584 Optional<Channel> channel = getChannel(network.get(), channelNotJoined.channel());
585 if (!channel.isPresent()) {
586 eventBus.post(new GenericMessage(format("Could not join %s but didn’t try to join, either.", channel.get())));
590 /* remove all bots for this channel, we might have been kicked. */
591 Collection<Bot> botsToRemove = networkBots.row(network.get())
593 .filter(bot -> bot.channel()
594 .equalsIgnoreCase(channel.get().name()))
595 .collect(Collectors.toSet());
596 botsToRemove.stream()
597 .forEach(bot -> networkBots.row(network.get())
598 .remove(bot.name()));
600 if (channelNotJoined.reason() == registeredNicknamesOnly) {
601 channels.remove(channel.get());
602 eventBus.post(new GenericMessage(
603 format("Not trying to join %s anymore.", channel.get())));
606 if (channelNotJoined.reason() == banned) {
607 channelBanManager.ban(channel.get());
608 eventBus.post(new GenericMessage(
609 format("Banned from %s, suspending join for a day.",
614 eventBus.post(new GenericMessage(
615 format("Could not join %s: %s", channelNotJoined.channel(),
616 channelNotJoined.reason())));
620 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
623 * The channel left event
626 public void channelLeft(ChannelLeft channelLeft) {
627 Optional<Network> network = getNetwork(channelLeft.connection());
628 if (!network.isPresent()) {
632 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
634 /* maybe it was us? */
635 if (channelLeft.connection().isSource(channelLeft.client())) {
636 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
637 if (!channel.isPresent()) {
638 /* maybe it was an extra channel? */
639 channel = getExtraChannel(network.get(), channelLeft.channel());
640 if (!channel.isPresent()) {
641 /* okay, whatever. */
645 extraChannels.remove(channel);
647 channels.remove(channel.get());
650 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
656 networkBots.remove(network.get(), channelLeft.client().nick().get());
660 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
661 Optional<Network> network = getNetwork(kickedFromChannel.connection());
662 if (!network.isPresent()) {
666 /* have we been kicked? */
667 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
668 Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
669 if (!channel.isPresent()) {
670 /* maybe it was an extra channel? */
671 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
672 if (!channel.isPresent()) {
673 /* okay, whatever. */
677 extraChannels.remove(channel);
679 channels.remove(channel.get());
681 eventBus.post(new GenericMessage(format(
682 "Kicked from %s by %s: %s",
683 kickedFromChannel.channel(),
684 kickedFromChannel.kicker(),
685 kickedFromChannel.reason().or("<unknown>")
690 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
691 return connection.nickname().equalsIgnoreCase(nickname);
695 * Removes a client (which may be a bot) from the table of known bots.
698 * The client quit event
701 public void clientQuit(ClientQuit clientQuit) {
702 Optional<Network> network = getNetwork(clientQuit.connection());
703 if (!network.isPresent()) {
707 networkBots.remove(network.get(), clientQuit.client().nick().get());
711 * If the nickname of a bit changes, remove it from the old name and store it
712 * under the new name.
714 * @param nicknameChanged
715 * The nickname changed event
718 public void nicknameChanged(NicknameChanged nicknameChanged) {
719 Optional<Network> network = getNetwork(nicknameChanged.connection());
720 if (!network.isPresent()) {
724 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
729 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
733 * If a message on a channel is received, it is parsed for pack information
734 * with is then added to a bot.
736 * @param channelMessageReceived
737 * The channel message received event
740 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
741 String message = getDefaultInstance().clean(channelMessageReceived.message());
742 if (!message.startsWith("#")) {
743 /* most probably not a pack announcement. */
747 Optional<Network> network = getNetwork(channelMessageReceived.connection());
748 if (!network.isPresent()) {
749 /* message for unknown connection? */
753 /* parse pack information. */
754 Optional<Pack> pack = parsePack(message);
755 if (!pack.isPresent()) {
760 synchronized (networkBots) {
761 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
762 bot = new Bot(network.get(), channelMessageReceived.channel(),
763 channelMessageReceived.source().nick().get());
764 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
765 eventBus.post(new BotAdded(bot));
767 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
772 bot.addPack(pack.get());
773 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
777 * Forward all private messages to every console.
779 * @param privateMessageReceived
780 * The private message recevied event
783 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
784 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
788 * Sends a message to all console when a notice was received.
790 * @param privateNoticeReceived
791 * The notice received event
794 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
795 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
796 if (!network.isPresent()) {
800 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.source(), network.get(), privateNoticeReceived.text())));
804 * Starts a DCC download.
806 * @param dccSendReceived
810 public void dccSendReceived(final DccSendReceived dccSendReceived) {
811 final Optional<Network> network = getNetwork(dccSendReceived.connection());
812 if (!network.isPresent()) {
816 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
817 if (packDownloads.isEmpty()) {
818 /* unknown download, ignore. */
822 /* check if it’s already downloading. */
823 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
824 if (!runningDownloads.isEmpty()) {
825 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
829 /* locate the correct download. */
830 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
833 public boolean apply(Download download) {
834 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
838 /* we did not request this download. */
839 if (requestedDownload.isEmpty()) {
843 Download download = requestedDownload.iterator().next();
845 /* check if the file already exists. */
846 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
847 if (outputFile.exists()) {
848 long existingFileSize = outputFile.length();
850 /* file already complete? */
851 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
852 /* file is apparently already complete. just move it. */
853 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
854 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
856 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
859 /* remove download. */
860 downloads.removeAll(download.pack().name());
864 /* file not complete yet, DCC resume it. */
866 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
867 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
868 } catch (IOException ioe1) {
869 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
875 /* file does not exist, start the download. */
877 OutputStream fileOutputStream = new FileOutputStream(outputFile);
878 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
879 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
880 dccReceivers.add(dccReceiver);
882 eventBus.post(new DownloadStarted(download));
883 } catch (FileNotFoundException fnfe1) {
884 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
889 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
890 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
891 if (!network.isPresent()) {
895 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
896 if (packDownloads.isEmpty()) {
897 /* unknown download, ignore. */
901 /* check if it’s already downloading. */
902 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
903 if (!runningDownloads.isEmpty()) {
904 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
908 /* locate the correct download. */
909 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
912 public boolean apply(Download download) {
913 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
917 /* we did not request this download. */
918 if (requestedDownload.isEmpty()) {
922 Download download = requestedDownload.iterator().next();
925 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
926 if (outputFile.length() != dccAcceptReceived.position()) {
927 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
928 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()));
930 downloads.removeAll(download.pack().name());
933 OutputStream outputStream = new FileOutputStream(outputFile, true);
934 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
935 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
936 dccReceivers.add(dccReceiver);
938 eventBus.post(new DownloadStarted(download));
939 } catch (FileNotFoundException fnfe1) {
944 * Closes the output stream of the download and moves the file to the final
947 * @param dccDownloadFinished
948 * The DCC download finished event
951 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
953 /* locate the correct download. */
954 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
955 if (requestedDownload.isEmpty()) {
956 /* this seems wrong. */
957 logger.warn("Download finished but could not be located.");
960 Download download = requestedDownload.iterator().next();
963 download.outputStream().close();
964 File file = new File(download.filename());
965 file.renameTo(new File(finalDirectory, download.pack().name()));
966 eventBus.post(new DownloadFinished(download));
967 dccReceivers.remove(dccDownloadFinished.dccReceiver());
968 downloads.removeAll(download.pack().name());
969 } catch (IOException ioe1) {
970 /* TODO - handle all the errors. */
971 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
976 * Closes the output stream and notifies all listeners of the failure.
978 * @param dccDownloadFailed
979 * The DCC download failed event
982 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
984 /* locate the correct download. */
985 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
986 if (requestedDownload.isEmpty()) {
987 /* this seems wrong. */
988 logger.warn("Download finished but could not be located.");
991 Download download = requestedDownload.iterator().next();
994 Closeables.close(download.outputStream(), true);
995 eventBus.post(new DownloadFailed(download));
996 dccReceivers.remove(dccDownloadFailed.dccReceiver());
997 downloads.removeAll(download.pack().name());
998 } catch (IOException ioe1) {
999 /* swallow silently. */
1004 public void replyReceived(ReplyReceived replyReceived) {
1005 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
1013 * Returns the download of the given pack from the given bot.
1016 * The pack being downloaded
1018 * The bot the pack is being downloaded from
1019 * @return The download, or {@link Optional#absent()} if the download could not
1022 private Optional<Download> getDownload(Pack pack, Bot bot) {
1023 if (!downloads.containsKey(pack.name())) {
1024 return Optional.absent();
1026 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
1027 if (download.bot().equals(bot)) {
1028 return Optional.of(download);
1031 return Optional.absent();
1035 * Searches all current connections for the given connection, returning the
1036 * associated network.
1039 * The connection to get the network for
1040 * @return The network belonging to the connection, or {@link
1041 * Optional#absent()}
1043 private Optional<Network> getNetwork(Connection connection) {
1044 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
1045 if (networkConnectionEntry.getValue().equals(connection)) {
1046 return Optional.of(networkConnectionEntry.getKey());
1049 return Optional.absent();
1053 * Returns the configured channel for the given network and name.
1056 * The network the channel is located on
1057 * @param channelName
1058 * The name of the channel
1059 * @return The configured channel, or {@link Optional#absent()} if no
1060 * configured channel matching the given network and name was found
1062 public Optional<Channel> getChannel(Network network, String channelName) {
1063 for (Channel channel : channels) {
1064 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1065 return Optional.of(channel);
1068 return Optional.absent();
1072 * Returns the extra channel for the given network and name.
1075 * The network the channel is located on
1076 * @param channelName
1077 * The name of the channel
1078 * @return The extra channel, or {@link Optional#absent()} if no extra channel
1079 * matching the given network and name was found
1081 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1082 for (Channel channel : extraChannels) {
1083 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1084 return Optional.of(channel);
1087 return Optional.absent();
1091 * Parses {@link Pack} information from the given message.
1094 * The message to parse pack information from
1095 * @return The parsed pack, or {@link Optional#absent()} if the message could
1096 * not be parsed into a pack
1098 private Optional<Pack> parsePack(String message) {
1099 int squareOpen = message.indexOf('[');
1100 int squareClose = message.indexOf(']', squareOpen);
1101 if ((squareOpen == -1) && (squareClose == -1)) {
1102 return Optional.absent();
1104 String packSize = message.substring(squareOpen + 1, squareClose);
1105 String packName = message.substring(message.lastIndexOf(' ') + 1);
1106 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1107 return Optional.of(new Pack(packIndex, packSize, packName));