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.HashSet;
35 import java.util.Iterator;
36 import java.util.List;
38 import java.util.Map.Entry;
40 import java.util.TreeMap;
41 import java.util.concurrent.TimeUnit;
42 import java.util.function.Function;
43 import java.util.stream.Collectors;
45 import net.pterodactylus.irc.Connection;
46 import net.pterodactylus.irc.ConnectionFactory;
47 import net.pterodactylus.irc.DccReceiver;
48 import net.pterodactylus.irc.DefaultConnection;
49 import net.pterodactylus.irc.event.ChannelJoined;
50 import net.pterodactylus.irc.event.ChannelLeft;
51 import net.pterodactylus.irc.event.ChannelMessageReceived;
52 import net.pterodactylus.irc.event.ChannelNotJoined;
53 import net.pterodactylus.irc.event.ClientQuit;
54 import net.pterodactylus.irc.event.ConnectionClosed;
55 import net.pterodactylus.irc.event.ConnectionEstablished;
56 import net.pterodactylus.irc.event.ConnectionFailed;
57 import net.pterodactylus.irc.event.DccAcceptReceived;
58 import net.pterodactylus.irc.event.DccDownloadFailed;
59 import net.pterodactylus.irc.event.DccDownloadFinished;
60 import net.pterodactylus.irc.event.DccSendReceived;
61 import net.pterodactylus.irc.event.KickedFromChannel;
62 import net.pterodactylus.irc.event.NicknameChanged;
63 import net.pterodactylus.irc.event.PrivateMessageReceived;
64 import net.pterodactylus.irc.event.PrivateNoticeReceived;
65 import net.pterodactylus.irc.event.ReplyReceived;
66 import net.pterodactylus.irc.util.RandomNickname;
67 import net.pterodactylus.xdcc.core.event.BotAdded;
68 import net.pterodactylus.xdcc.core.event.CoreStarted;
69 import net.pterodactylus.xdcc.core.event.DownloadFailed;
70 import net.pterodactylus.xdcc.core.event.DownloadFinished;
71 import net.pterodactylus.xdcc.core.event.DownloadStarted;
72 import net.pterodactylus.xdcc.core.event.GenericError;
73 import net.pterodactylus.xdcc.core.event.GenericMessage;
74 import net.pterodactylus.xdcc.core.event.MessageReceived;
75 import net.pterodactylus.xdcc.data.Bot;
76 import net.pterodactylus.xdcc.data.Channel;
77 import net.pterodactylus.xdcc.data.ConnectedNetwork;
78 import net.pterodactylus.xdcc.data.Download;
79 import net.pterodactylus.xdcc.data.Network;
80 import net.pterodactylus.xdcc.data.Pack;
81 import net.pterodactylus.xdcc.data.Server;
83 import com.google.common.base.Optional;
84 import com.google.common.base.Predicate;
85 import com.google.common.collect.FluentIterable;
86 import com.google.common.collect.HashBasedTable;
87 import com.google.common.collect.HashMultimap;
88 import com.google.common.collect.ImmutableList;
89 import com.google.common.collect.ImmutableSet;
90 import com.google.common.collect.Lists;
91 import com.google.common.collect.Maps;
92 import com.google.common.collect.Multimap;
93 import com.google.common.collect.Sets;
94 import com.google.common.collect.Table;
95 import com.google.common.eventbus.EventBus;
96 import com.google.common.eventbus.Subscribe;
97 import com.google.common.io.Closeables;
98 import com.google.common.util.concurrent.AbstractExecutionThreadService;
99 import com.google.inject.Inject;
100 import org.apache.log4j.Logger;
103 * The core of XDCC Downloader.
105 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
107 public class Core extends AbstractExecutionThreadService {
110 private static final Logger logger = Logger.getLogger(Core.class.getName());
112 private final Object syncObject = new Object();
113 /** The event bus. */
114 private final EventBus eventBus;
115 private final ConnectionFactory connectionFactory;
116 private final ChannelBanManager channelBanManager =
117 new ChannelBanManager();
118 private final ConnectionBackoff connectionBackoff = new ConnectionBackoff();
120 /** The temporary directory to download files to. */
121 private final String temporaryDirectory;
123 /** The directory to move finished downloads to. */
124 private final String finalDirectory;
126 /** The channels that should be monitored. */
127 private final Collection<Channel> channels = Sets.newHashSet();
129 /** The channels that are currentlymonitored. */
130 private final Collection<Channel> joinedChannels = Sets.newHashSet();
131 private final Set<Channel> channelsBeingJoined = new HashSet<>();
133 /** The channels that are joined but not configured. */
134 private final Collection<Channel> extraChannels = Sets.newHashSet();
136 /** The current network connections. */
137 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
139 /** The currently known bots. */
140 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
142 /** The current downloads. */
143 private final Multimap<String, Download> downloads = HashMultimap.create();
145 /** The current DCC receivers. */
146 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
149 * Creates a new core.
153 * @param temporaryDirectory
154 * The directory to download files to
155 * @param finalDirectory
156 * The directory to move finished files to
159 public Core(EventBus eventBus, ConnectionFactory connectionFactory, String temporaryDirectory, String finalDirectory) {
160 this.eventBus = eventBus;
161 this.connectionFactory = connectionFactory;
162 this.temporaryDirectory = temporaryDirectory;
163 this.finalDirectory = finalDirectory;
171 * Returns all currently known connections.
173 * @return All currently known connections
175 public Collection<Connection> connections() {
176 return networkConnections.values();
180 * Returns all defined networks.
182 * @return All defined networks
184 public Collection<Network> networks() {
185 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
189 * Returns all connected networks.
191 * @return All connected networks
193 public Collection<ConnectedNetwork> connectedNetworks() {
194 return networkConnections.entrySet().stream().map((entry) -> {
195 Network network = entry.getKey();
196 Collection<Bot> bots = networkBots.row(network).values();
197 int packCount = bots.stream().mapToInt((bot) -> bot.packs().size()).reduce((a, b) -> a + b).orElse(0);
198 return new ConnectedNetwork(network, entry.getValue().hostname(),
199 entry.getValue().port(), entry.getValue().nickname(),
201 .filter((channel) -> channel.network()
204 .collect(Collectors.<String>toList()),
205 extraChannels.stream()
206 .filter((channel) -> channel.network()
209 .collect(Collectors.<String>toList()),
210 bots.size(), packCount);
211 }).collect(Collectors.<ConnectedNetwork>toList());
215 * Returns all configured channels. Due to various circumstances, configured
216 * channels might not actually be joined.
218 * @return All configured channels
220 public Collection<Channel> channels() {
221 return ImmutableSet.copyOf(channels);
225 * Returns all currently joined channels.
227 * @return All currently joined channels
229 public Collection<Channel> joinedChannels() {
230 return ImmutableSet.copyOf(joinedChannels);
234 * Returns all currently joined channels that are not configured.
236 * @return All currently joined but not configured channels
238 public Collection<Channel> extraChannels() {
239 return ImmutableSet.copyOf(extraChannels);
243 * Returns all currently known bots.
245 * @return All currently known bots
247 public Collection<Bot> bots() {
248 return networkBots.values();
252 * Returns all currently running downloads.
254 * @return All currently running downloads
256 public Collection<Download> downloads() {
257 return downloads.values();
265 * Adds a channel to monitor.
268 * The channel to monitor
270 public void addChannel(Channel channel) {
271 channels.add(channel);
275 * Fetches the given pack from the given bot.
278 * The bot to fetch the pack from
282 public void fetch(Bot bot, Pack pack) {
283 Connection connection = networkConnections.get(bot.network());
284 if (connection == null) {
288 /* check if we are already downloading the file? */
289 if (downloads.containsKey(pack.name())) {
290 Collection<Download> packDownloads = downloads.get(pack.name());
291 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
292 if (!runningDownloads.isEmpty()) {
293 Download download = runningDownloads.iterator().next();
294 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
297 StringBuilder bots = new StringBuilder();
298 for (Download download : packDownloads) {
299 if (bots.length() > 0) {
302 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
304 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
307 Download download = new Download(bot, pack);
308 downloads.put(pack.name(), download);
311 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
312 } catch (IOException ioe1) {
313 logger.warn("Could not send message to bot!", ioe1);
318 * Cancels the download of the given pack from the given bot.
321 * The bot the pack is being downloaded from
323 * The pack being downloaded
325 public void cancelDownload(Bot bot, Pack pack) {
326 Optional<Download> download = getDownload(pack, bot);
327 if (!download.isPresent()) {
331 /* get connection. */
332 Connection connection = networkConnections.get(bot.network());
333 if (connection == null) {
334 /* request for unknown network? */
338 /* stop the DCC receiver. */
339 if (download.get().dccReceiver() != null) {
340 download.get().dccReceiver().stop();
342 /* remove download if it hasn’t started yet. */
343 downloads.remove(pack.name(), download.get());
346 /* remove the request from the bot, too. */
348 connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
349 } catch (IOException ioe1) {
350 logger.warn(String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
355 * Closes the given connection.
358 * The connection to close
360 public void closeConnection(Connection connection) {
363 } catch (IOException ioe1) {
369 // ABSTRACTIDLESERVICE METHODS
373 protected void startUp() {
374 for (Channel channel : channels) {
375 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
376 connectNetwork(channel.network());
379 /* notify listeners. */
380 eventBus.post(new CoreStarted(this));
384 protected void run() throws Exception {
385 while (isRunning()) {
387 Set<Channel> missingChannels = new HashSet<>();
388 for (Channel channel : channels) {
389 if (joinedChannels.contains(channel) || channelsBeingJoined.contains(channel)) {
392 if (channelBanManager.isBanned(channel)) {
395 if (networkConnections.containsKey(channel.network())) {
396 if (networkConnections.get(channel.network()).established()) {
397 missingChannels.add(channel);
401 Set<Network> missingNetworks = missingChannels.stream()
402 .map(Channel::network)
404 .filter((network) -> !networkConnections.containsKey(network))
405 .collect(Collectors.toSet());
407 if (!missingChannels.isEmpty()) {
408 for (Channel missingChannel : missingChannels) {
409 Network network = missingChannel.network();
410 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", missingChannel.name(), network)));
412 channelsBeingJoined.add(missingChannel);
413 networkConnections.get(network).joinChannel(missingChannel.name());
414 } catch (IOException ioe1) {
415 logger.warn(String.format("Could not join %s on %s!", missingChannel.name(), network.name()), ioe1);
418 } else if (missingNetworks.isEmpty()) {
419 synchronized (syncObject) {
421 syncObject.wait(TimeUnit.MINUTES.toMillis(1));
422 } catch (InterruptedException ie1) {
429 Map<Long, Network> timesForNextConnects = new TreeMap<>(missingNetworks.stream()
430 .collect(Collectors.toMap(connectionBackoff::getBackoff, Function.identity(), (network, ignore) -> network)));
432 Entry<Long, Network> firstNetwork = timesForNextConnects.entrySet().stream().findFirst().get();
433 if (firstNetwork.getKey() > 0) {
434 eventBus.post(new GenericMessage(String.format("Waiting %d seconds to connect to %s...", TimeUnit.MILLISECONDS.toMinutes(firstNetwork.getKey()), firstNetwork.getValue().name())));
435 synchronized (syncObject) {
437 syncObject.wait(firstNetwork.getKey());
438 } catch (InterruptedException ie1) {
447 connectNetwork(firstNetwork.getValue());
452 protected void triggerShutdown() {
453 synchronized (syncObject) {
454 syncObject.notifyAll();
463 * Starts a new connection for the given network if no such connection exists
467 * The network to connect to
469 private void connectNetwork(Network network) {
470 if (!networkConnections.containsKey(network)) {
471 /* select a random server. */
472 List<Server> servers = Lists.newArrayList(network.servers());
473 if (servers.isEmpty()) {
474 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
477 Server server = servers.get((int) (Math.random() * servers.size()));
478 Connection connection = connectionFactory.createConnection(server.hostname(),
479 server.unencryptedPorts().iterator().next());
480 connection.username(RandomNickname.get()).realName(RandomNickname.get());
481 networkConnections.put(network, connection);
487 * Removes the given connection and all its channels and bots.
490 * The connection to remove
492 private void removeConnection(Connection connection) {
493 Optional<Network> network = getNetwork(connection);
494 if (!network.isPresent()) {
497 networkConnections.remove(network.get());
498 if (!connection.established()) {
502 /* find all channels that need to be removed. */
503 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
504 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
505 Channel joinedChannel = channelIterator.next();
506 if (!joinedChannel.network().equals(network.get())) {
510 channelIterator.remove();
514 /* now remove all bots for that network. */
515 Map<String, Bot> bots = networkBots.row(network.get());
516 int botCount = bots.size();
518 for (Bot bot : bots.values()) {
519 packCount += bot.packs().size();
522 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
530 * If a connection to a network has been established, the channels associated
531 * with this network are joined.
533 * @param connectionEstablished
534 * The connection established event
537 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
539 /* get network for connection. */
540 Optional<Network> network = getNetwork(connectionEstablished.connection());
543 if (!network.isPresent()) {
544 eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
548 connectionBackoff.connectionSuccessful(network.get());
549 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
551 /* join all channels on this network. */
552 for (Channel channel : channels) {
553 if (channel.network().equals(network.get())) {
555 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
556 connectionEstablished.connection().joinChannel(channel.name());
557 } catch (IOException ioe1) {
558 logger.warn(String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
565 * Remove all data stored for a network if the connection is closed.
567 * @param connectionClosed
568 * The connection closed event
571 public void connectionClosed(ConnectionClosed connectionClosed) {
572 connectionBackoff.connectionFailed(getNetwork(connectionClosed.connection()).get());
573 removeConnection(connectionClosed.connection());
574 synchronized (syncObject) {
575 syncObject.notifyAll();
577 eventBus.post(new GenericMessage(String.format("Connection closed by %s.", connectionClosed.connection().hostname())));
581 * Remove all data stored for a network if the connection fails.
583 * @param connectionFailed
584 * The connection failed event
587 public void connectionFailed(ConnectionFailed connectionFailed) {
588 connectionBackoff.connectionFailed(getNetwork(connectionFailed.connection()).get());
589 removeConnection(connectionFailed.connection());
590 synchronized (syncObject) {
591 syncObject.notifyAll();
593 eventBus.post(new GenericMessage(String.format("Could not connect to %s: %s.", connectionFailed.connection().hostname(), connectionFailed.cause())));
597 * Shows a message when a channel was joined by us.
599 * @param channelJoined
600 * The channel joined event
603 public void channelJoined(ChannelJoined channelJoined) {
604 if (channelJoined.connection().isSource(channelJoined.client())) {
605 Optional<Network> network = getNetwork(channelJoined.connection());
606 if (!network.isPresent()) {
610 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
611 if (!channel.isPresent()) {
612 /* it’s an extra channel. */
613 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
614 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
618 channelBanManager.unban(channel.get());
619 joinedChannels.add(channel.get());
620 channelsBeingJoined.remove(channel.get());
621 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
626 public void channelNotJoined(ChannelNotJoined channelNotJoined) {
627 Optional<Network> network = getNetwork(channelNotJoined.connection());
628 if (!network.isPresent()) {
632 Optional<Channel> channel = getChannel(network.get(), channelNotJoined.channel());
633 if (!channel.isPresent()) {
634 eventBus.post(new GenericMessage(format("Could not join %s but didn’t try to join, either.", channelNotJoined.channel())));
638 channelsBeingJoined.remove(channel.get());
639 synchronized (syncObject) {
640 syncObject.notifyAll();
643 /* remove all bots for this channel, we might have been kicked. */
644 Collection<Bot> botsToRemove = networkBots.row(network.get())
646 .filter(bot -> bot.channel()
647 .equalsIgnoreCase(channel.get().name()))
648 .collect(Collectors.toSet());
649 botsToRemove.stream()
650 .forEach(bot -> networkBots.row(network.get())
651 .remove(bot.name()));
653 if (channelNotJoined.reason() == registeredNicknamesOnly) {
654 channels.remove(channel.get());
655 eventBus.post(new GenericMessage(
656 format("Not trying to join %s anymore.", channel.get())));
659 if (channelNotJoined.reason() == banned) {
660 channelBanManager.ban(channel.get());
661 eventBus.post(new GenericMessage(
662 format("Banned from %s, suspending join for a day.",
667 eventBus.post(new GenericMessage(
668 format("Could not join %s: %s", channelNotJoined.channel(),
669 channelNotJoined.reason())));
673 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
676 * The channel left event
679 public void channelLeft(ChannelLeft channelLeft) {
680 Optional<Network> network = getNetwork(channelLeft.connection());
681 if (!network.isPresent()) {
685 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
687 /* maybe it was us? */
688 if (channelLeft.connection().isSource(channelLeft.client())) {
689 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
690 if (!channel.isPresent()) {
691 /* maybe it was an extra channel? */
692 channel = getExtraChannel(network.get(), channelLeft.channel());
693 if (!channel.isPresent()) {
694 /* okay, whatever. */
698 extraChannels.remove(channel);
700 channels.remove(channel.get());
702 synchronized (syncObject) {
703 syncObject.notifyAll();
706 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
712 networkBots.remove(network.get(), channelLeft.client().nick().get());
716 public void kickedFromChannel(KickedFromChannel kickedFromChannel) {
717 Optional<Network> network = getNetwork(kickedFromChannel.connection());
718 if (!network.isPresent()) {
722 /* have we been kicked? */
723 if (nicknameMatchesConnection(kickedFromChannel.connection(), kickedFromChannel.kickee())) {
724 Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
725 if (!channel.isPresent()) {
726 /* maybe it was an extra channel? */
727 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
728 if (!channel.isPresent()) {
729 /* okay, whatever. */
733 extraChannels.remove(channel.get());
735 joinedChannels.remove(channel.get());
737 synchronized (syncObject) {
738 syncObject.notifyAll();
740 eventBus.post(new GenericMessage(format(
741 "Kicked from %s by %s: %s",
742 kickedFromChannel.channel(),
743 kickedFromChannel.kicker(),
744 kickedFromChannel.reason().or("<unknown>")
749 private boolean nicknameMatchesConnection(Connection connection, String nickname) {
750 return connection.nickname().equalsIgnoreCase(nickname);
754 * Removes a client (which may be a bot) from the table of known bots.
757 * The client quit event
760 public void clientQuit(ClientQuit clientQuit) {
761 Optional<Network> network = getNetwork(clientQuit.connection());
762 if (!network.isPresent()) {
766 networkBots.remove(network.get(), clientQuit.client().nick().get());
770 * If the nickname of a bit changes, remove it from the old name and store it
771 * under the new name.
773 * @param nicknameChanged
774 * The nickname changed event
777 public void nicknameChanged(NicknameChanged nicknameChanged) {
778 Optional<Network> network = getNetwork(nicknameChanged.connection());
779 if (!network.isPresent()) {
783 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
788 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
792 * If a message on a channel is received, it is parsed for pack information
793 * with is then added to a bot.
795 * @param channelMessageReceived
796 * The channel message received event
799 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
800 String message = getDefaultInstance().clean(channelMessageReceived.message());
801 if (!message.startsWith("#")) {
802 /* most probably not a pack announcement. */
806 Optional<Network> network = getNetwork(channelMessageReceived.connection());
807 if (!network.isPresent()) {
808 /* message for unknown connection? */
812 /* parse pack information. */
813 Optional<Pack> pack = parsePack(message);
814 if (!pack.isPresent()) {
819 synchronized (networkBots) {
820 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
821 bot = new Bot(network.get(), channelMessageReceived.channel(),
822 channelMessageReceived.source().nick().get());
823 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
824 eventBus.post(new BotAdded(bot));
826 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
831 bot.addPack(pack.get());
832 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
836 * Forward all private messages to every console.
838 * @param privateMessageReceived
839 * The private message recevied event
842 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
843 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
847 * Sends a message to all console when a notice was received.
849 * @param privateNoticeReceived
850 * The notice received event
853 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
854 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
855 if (!network.isPresent()) {
859 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.source(), network.get(), privateNoticeReceived.text())));
863 * Starts a DCC download.
865 * @param dccSendReceived
869 public void dccSendReceived(final DccSendReceived dccSendReceived) {
870 final Optional<Network> network = getNetwork(dccSendReceived.connection());
871 if (!network.isPresent()) {
875 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
876 if (packDownloads.isEmpty()) {
877 /* unknown download, ignore. */
881 /* check if it’s already downloading. */
882 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
883 if (!runningDownloads.isEmpty()) {
884 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
888 /* locate the correct download. */
889 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
892 public boolean apply(Download download) {
893 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
897 /* we did not request this download. */
898 if (requestedDownload.isEmpty()) {
902 Download download = requestedDownload.iterator().next();
904 /* check if the file already exists. */
905 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
906 if (outputFile.exists()) {
907 long existingFileSize = outputFile.length();
909 /* file already complete? */
910 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
911 /* file is apparently already complete. just move it. */
912 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
913 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
915 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
918 /* remove download. */
919 downloads.removeAll(download.pack().name());
923 /* file not complete yet, DCC resume it. */
925 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
926 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
927 } catch (IOException ioe1) {
928 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
934 /* file does not exist, start the download. */
936 OutputStream fileOutputStream = new FileOutputStream(outputFile);
937 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
938 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
939 dccReceivers.add(dccReceiver);
941 eventBus.post(new DownloadStarted(download));
942 } catch (FileNotFoundException fnfe1) {
943 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
948 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
949 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
950 if (!network.isPresent()) {
954 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
955 if (packDownloads.isEmpty()) {
956 /* unknown download, ignore. */
960 /* check if it’s already downloading. */
961 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
962 if (!runningDownloads.isEmpty()) {
963 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
967 /* locate the correct download. */
968 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
971 public boolean apply(Download download) {
972 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
976 /* we did not request this download. */
977 if (requestedDownload.isEmpty()) {
981 Download download = requestedDownload.iterator().next();
984 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
985 if (outputFile.length() != dccAcceptReceived.position()) {
986 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
987 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()));
989 downloads.removeAll(download.pack().name());
992 OutputStream outputStream = new FileOutputStream(outputFile, true);
993 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
994 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
995 dccReceivers.add(dccReceiver);
997 eventBus.post(new DownloadStarted(download));
998 } catch (FileNotFoundException fnfe1) {
1003 * Closes the output stream of the download and moves the file to the final
1006 * @param dccDownloadFinished
1007 * The DCC download finished event
1010 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
1012 /* locate the correct download. */
1013 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
1014 if (requestedDownload.isEmpty()) {
1015 /* this seems wrong. */
1016 logger.warn("Download finished but could not be located.");
1019 Download download = requestedDownload.iterator().next();
1022 download.outputStream().close();
1023 File file = new File(download.filename());
1024 file.renameTo(new File(finalDirectory, download.pack().name()));
1025 eventBus.post(new DownloadFinished(download));
1026 dccReceivers.remove(dccDownloadFinished.dccReceiver());
1027 downloads.removeAll(download.pack().name());
1028 } catch (IOException ioe1) {
1029 /* TODO - handle all the errors. */
1030 logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
1035 * Closes the output stream and notifies all listeners of the failure.
1037 * @param dccDownloadFailed
1038 * The DCC download failed event
1041 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
1043 /* locate the correct download. */
1044 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
1045 if (requestedDownload.isEmpty()) {
1046 /* this seems wrong. */
1047 logger.warn("Download finished but could not be located.");
1050 Download download = requestedDownload.iterator().next();
1053 Closeables.close(download.outputStream(), true);
1054 eventBus.post(new DownloadFailed(download));
1055 dccReceivers.remove(dccDownloadFailed.dccReceiver());
1056 downloads.removeAll(download.pack().name());
1057 } catch (IOException ioe1) {
1058 /* swallow silently. */
1063 public void replyReceived(ReplyReceived replyReceived) {
1064 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
1072 * Returns the download of the given pack from the given bot.
1075 * The pack being downloaded
1077 * The bot the pack is being downloaded from
1078 * @return The download, or {@link Optional#absent()} if the download could not
1081 private Optional<Download> getDownload(Pack pack, Bot bot) {
1082 if (!downloads.containsKey(pack.name())) {
1083 return Optional.absent();
1085 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
1086 if (download.bot().equals(bot)) {
1087 return Optional.of(download);
1090 return Optional.absent();
1094 * Searches all current connections for the given connection, returning the
1095 * associated network.
1098 * The connection to get the network for
1099 * @return The network belonging to the connection, or {@link
1100 * Optional#absent()}
1102 private Optional<Network> getNetwork(Connection connection) {
1103 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
1104 if (networkConnectionEntry.getValue().equals(connection)) {
1105 return Optional.of(networkConnectionEntry.getKey());
1108 return Optional.absent();
1112 * Returns the configured channel for the given network and name.
1115 * The network the channel is located on
1116 * @param channelName
1117 * The name of the channel
1118 * @return The configured channel, or {@link Optional#absent()} if no
1119 * configured channel matching the given network and name was found
1121 public Optional<Channel> getChannel(Network network, String channelName) {
1122 for (Channel channel : channels) {
1123 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1124 return Optional.of(channel);
1127 return Optional.absent();
1131 * Returns the extra channel for the given network and name.
1134 * The network the channel is located on
1135 * @param channelName
1136 * The name of the channel
1137 * @return The extra channel, or {@link Optional#absent()} if no extra channel
1138 * matching the given network and name was found
1140 public Optional<Channel> getExtraChannel(Network network, String channelName) {
1141 for (Channel channel : extraChannels) {
1142 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1143 return Optional.of(channel);
1146 return Optional.absent();
1150 * Parses {@link Pack} information from the given message.
1153 * The message to parse pack information from
1154 * @return The parsed pack, or {@link Optional#absent()} if the message could
1155 * not be parsed into a pack
1157 private Optional<Pack> parsePack(String message) {
1158 int squareOpen = message.indexOf('[');
1159 int squareClose = message.indexOf(']', squareOpen);
1160 if ((squareOpen == -1) && (squareClose == -1)) {
1161 return Optional.absent();
1163 String packSize = message.substring(squareOpen + 1, squareClose);
1164 String packName = message.substring(message.lastIndexOf(' ') + 1);
1165 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1166 return Optional.of(new Pack(packIndex, packSize, packName));