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 /* remove all bots for this channel, we might have been kicked. */
581 Collection<Bot> botsToRemove = networkBots.row(network.get())
583 .filter(bot -> bot.channel()
584 .equalsIgnoreCase(channel.get().name()))
585 .collect(Collectors.toSet());
586 botsToRemove.stream()
587 .forEach(bot -> networkBots.row(network.get())
588 .remove(bot.name()));
590 if (channelNotJoined.reason() == registeredNicknamesOnly) {
591 channels.remove(channel.get());
592 eventBus.post(new GenericMessage(
593 format("Not trying to join %s anymore.", channel.get())));
596 if (channelNotJoined.reason() == banned) {
597 channelBanManager.ban(channel.get());
598 eventBus.post(new GenericMessage(
599 format("Banned from %s, suspending join for a day.",
604 eventBus.post(new GenericMessage(
605 format("Could not join %s: %s", channelNotJoined.channel(),
606 channelNotJoined.reason())));
610 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
613 * The channel left event
616 public void channelLeft(ChannelLeft channelLeft) {
617 Optional<Network> network = getNetwork(channelLeft.connection());
618 if (!network.isPresent()) {
622 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
624 /* maybe it was us? */
625 if (channelLeft.connection().isSource(channelLeft.client())) {
626 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
627 if (!channel.isPresent()) {
628 /* maybe it was an extra channel? */
629 channel = getExtraChannel(network.get(), channelLeft.channel());
630 if (!channel.isPresent()) {
631 /* okay, whatever. */
635 extraChannels.remove(channel);
637 channels.remove(channel.get());
640 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
646 networkBots.remove(network.get(), channelLeft.client().nick().get());
650 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
651 Optional<Network> network = getNetwork(kickedFromChannel.connection());
652 if (!network.isPresent()) {
656 /* have we been kicked? */
657 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
658 Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
659 if (!channel.isPresent()) {
660 /* maybe it was an extra channel? */
661 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
662 if (!channel.isPresent()) {
663 /* okay, whatever. */
667 extraChannels.remove(channel);
669 channels.remove(channel.get());
671 eventBus.post(new GenericMessage(format(
672 "Kicked from %s by %s: %s",
673 kickedFromChannel.channel(),
674 kickedFromChannel.kicker(),
675 kickedFromChannel.reason().or("<unknown>")
680 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
681 return connection.nickname().equalsIgnoreCase(nickname);
685 * Removes a client (which may be a bot) from the table of known bots.
688 * The client quit event
691 public void clientQuit(ClientQuit clientQuit) {
692 Optional<Network> network = getNetwork(clientQuit.connection());
693 if (!network.isPresent()) {
697 networkBots.remove(network.get(), clientQuit.client().nick().get());
701 * If the nickname of a bit changes, remove it from the old name and store it
702 * under the new name.
704 * @param nicknameChanged
705 * The nickname changed event
708 public void nicknameChanged(NicknameChanged nicknameChanged) {
709 Optional<Network> network = getNetwork(nicknameChanged.connection());
710 if (!network.isPresent()) {
714 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
719 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
723 * If a message on a channel is received, it is parsed for pack information
724 * with is then added to a bot.
726 * @param channelMessageReceived
727 * The channel message received event
730 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
731 String message = getDefaultInstance().clean(channelMessageReceived.message());
732 if (!message.startsWith("#")) {
733 /* most probably not a pack announcement. */
737 Optional<Network> network = getNetwork(channelMessageReceived.connection());
738 if (!network.isPresent()) {
739 /* message for unknown connection? */
743 /* parse pack information. */
744 Optional<Pack> pack = parsePack(message);
745 if (!pack.isPresent()) {
750 synchronized (networkBots) {
751 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
752 bot = new Bot(network.get(), channelMessageReceived.channel(),
753 channelMessageReceived.source().nick().get());
754 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
755 eventBus.post(new BotAdded(bot));
757 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
762 bot.addPack(pack.get());
763 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
767 * Forward all private messages to every console.
769 * @param privateMessageReceived
770 * The private message recevied event
773 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
774 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
778 * Sends a message to all console when a notice was received.
780 * @param privateNoticeReceived
781 * The notice received event
784 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
785 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
786 if (!network.isPresent()) {
790 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.source(), network.get(), privateNoticeReceived.text())));
794 * Starts a DCC download.
796 * @param dccSendReceived
800 public void dccSendReceived(final DccSendReceived dccSendReceived) {
801 final Optional<Network> network = getNetwork(dccSendReceived.connection());
802 if (!network.isPresent()) {
806 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
807 if (packDownloads.isEmpty()) {
808 /* unknown download, ignore. */
812 /* check if it’s already downloading. */
813 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
814 if (!runningDownloads.isEmpty()) {
815 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
819 /* locate the correct download. */
820 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
823 public boolean apply(Download download) {
824 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
828 /* we did not request this download. */
829 if (requestedDownload.isEmpty()) {
833 Download download = requestedDownload.iterator().next();
835 /* check if the file already exists. */
836 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
837 if (outputFile.exists()) {
838 long existingFileSize = outputFile.length();
840 /* file already complete? */
841 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
842 /* file is apparently already complete. just move it. */
843 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
844 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
846 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
849 /* remove download. */
850 downloads.removeAll(download.pack().name());
854 /* file not complete yet, DCC resume it. */
856 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
857 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
858 } catch (IOException ioe1) {
859 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
865 /* file does not exist, start the download. */
867 OutputStream fileOutputStream = new FileOutputStream(outputFile);
868 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
869 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
870 dccReceivers.add(dccReceiver);
872 eventBus.post(new DownloadStarted(download));
873 } catch (FileNotFoundException fnfe1) {
874 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
879 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
880 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
881 if (!network.isPresent()) {
885 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
886 if (packDownloads.isEmpty()) {
887 /* unknown download, ignore. */
891 /* check if it’s already downloading. */
892 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
893 if (!runningDownloads.isEmpty()) {
894 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
898 /* locate the correct download. */
899 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
902 public boolean apply(Download download) {
903 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
907 /* we did not request this download. */
908 if (requestedDownload.isEmpty()) {
912 Download download = requestedDownload.iterator().next();
915 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
916 if (outputFile.length() != dccAcceptReceived.position()) {
917 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
918 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()));
920 downloads.removeAll(download.pack().name());
923 OutputStream outputStream = new FileOutputStream(outputFile, true);
924 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
925 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
926 dccReceivers.add(dccReceiver);
928 eventBus.post(new DownloadStarted(download));
929 } catch (FileNotFoundException fnfe1) {
934 * Closes the output stream of the download and moves the file to the final
937 * @param dccDownloadFinished
938 * The DCC download finished event
941 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
943 /* locate the correct download. */
944 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
945 if (requestedDownload.isEmpty()) {
946 /* this seems wrong. */
947 logger.warn("Download finished but could not be located.");
950 Download download = requestedDownload.iterator().next();
953 download.outputStream().close();
954 File file = new File(download.filename());
955 file.renameTo(new File(finalDirectory, download.pack().name()));
956 eventBus.post(new DownloadFinished(download));
957 dccReceivers.remove(dccDownloadFinished.dccReceiver());
958 downloads.removeAll(download.pack().name());
959 } catch (IOException ioe1) {
960 /* TODO - handle all the errors. */
961 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
966 * Closes the output stream and notifies all listeners of the failure.
968 * @param dccDownloadFailed
969 * The DCC download failed event
972 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
974 /* locate the correct download. */
975 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
976 if (requestedDownload.isEmpty()) {
977 /* this seems wrong. */
978 logger.warn("Download finished but could not be located.");
981 Download download = requestedDownload.iterator().next();
984 Closeables.close(download.outputStream(), true);
985 eventBus.post(new DownloadFailed(download));
986 dccReceivers.remove(dccDownloadFailed.dccReceiver());
987 downloads.removeAll(download.pack().name());
988 } catch (IOException ioe1) {
989 /* swallow silently. */
994 public void replyReceived(ReplyReceived replyReceived) {
995 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
1003 * Returns the download of the given pack from the given bot.
1006 * The pack being downloaded
1008 * The bot the pack is being downloaded from
1009 * @return The download, or {@link Optional#absent()} if the download could not
1012 private Optional<Download> getDownload(Pack pack, Bot bot) {
1013 if (!downloads.containsKey(pack.name())) {
1014 return Optional.absent();
1016 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
1017 if (download.bot().equals(bot)) {
1018 return Optional.of(download);
1021 return Optional.absent();
1025 * Searches all current connections for the given connection, returning the
1026 * associated network.
1029 * The connection to get the network for
1030 * @return The network belonging to the connection, or {@link
1031 * Optional#absent()}
1033 private Optional<Network> getNetwork(Connection connection) {
1034 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
1035 if (networkConnectionEntry.getValue().equals(connection)) {
1036 return Optional.of(networkConnectionEntry.getKey());
1039 return Optional.absent();
1043 * Returns the configured channel for the given network and name.
1046 * The network the channel is located on
1047 * @param channelName
1048 * The name of the channel
1049 * @return The configured channel, or {@link Optional#absent()} if no
1050 * configured channel matching the given network and name was found
1052 public Optional<Channel> getChannel(Network network, String channelName) {
1053 for (Channel channel : channels) {
1054 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1055 return Optional.of(channel);
1058 return Optional.absent();
1062 * Returns the extra channel for the given network and name.
1065 * The network the channel is located on
1066 * @param channelName
1067 * The name of the channel
1068 * @return The extra channel, or {@link Optional#absent()} if no extra channel
1069 * matching the given network and name was found
1071 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1072 for (Channel channel : extraChannels) {
1073 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1074 return Optional.of(channel);
1077 return Optional.absent();
1081 * Parses {@link Pack} information from the given message.
1084 * The message to parse pack information from
1085 * @return The parsed pack, or {@link Optional#absent()} if the message could
1086 * not be parsed into a pack
1088 private Optional<Pack> parsePack(String message) {
1089 int squareOpen = message.indexOf('[');
1090 int squareClose = message.indexOf(']', squareOpen);
1091 if ((squareOpen == -1) && (squareClose == -1)) {
1092 return Optional.absent();
1094 String packSize = message.substring(squareOpen + 1, squareClose);
1095 String packName = message.substring(message.lastIndexOf(' ') + 1);
1096 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1097 return Optional.of(new Pack(packIndex, packSize, packName));