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 net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
23 import java.io.FileNotFoundException;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.io.OutputStream;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.Map.Entry;
33 import java.util.concurrent.TimeUnit;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
37 import net.pterodactylus.irc.Connection;
38 import net.pterodactylus.irc.ConnectionBuilder;
39 import net.pterodactylus.irc.DccReceiver;
40 import net.pterodactylus.irc.event.ChannelJoined;
41 import net.pterodactylus.irc.event.ChannelLeft;
42 import net.pterodactylus.irc.event.ChannelMessageReceived;
43 import net.pterodactylus.irc.event.ClientQuit;
44 import net.pterodactylus.irc.event.ConnectionClosed;
45 import net.pterodactylus.irc.event.ConnectionEstablished;
46 import net.pterodactylus.irc.event.ConnectionFailed;
47 import net.pterodactylus.irc.event.DccAcceptReceived;
48 import net.pterodactylus.irc.event.DccDownloadFailed;
49 import net.pterodactylus.irc.event.DccDownloadFinished;
50 import net.pterodactylus.irc.event.DccSendReceived;
51 import net.pterodactylus.irc.event.NicknameChanged;
52 import net.pterodactylus.irc.event.PrivateMessageReceived;
53 import net.pterodactylus.irc.event.PrivateNoticeReceived;
54 import net.pterodactylus.irc.util.MessageCleaner;
55 import net.pterodactylus.irc.util.RandomNickname;
56 import net.pterodactylus.xdcc.core.event.BotAdded;
57 import net.pterodactylus.xdcc.core.event.CoreStarted;
58 import net.pterodactylus.xdcc.core.event.DownloadFailed;
59 import net.pterodactylus.xdcc.core.event.DownloadFinished;
60 import net.pterodactylus.xdcc.core.event.DownloadStarted;
61 import net.pterodactylus.xdcc.core.event.GenericError;
62 import net.pterodactylus.xdcc.core.event.GenericMessage;
63 import net.pterodactylus.xdcc.core.event.MessageReceived;
64 import net.pterodactylus.xdcc.data.Bot;
65 import net.pterodactylus.xdcc.data.Channel;
66 import net.pterodactylus.xdcc.data.Download;
67 import net.pterodactylus.xdcc.data.Network;
68 import net.pterodactylus.xdcc.data.Pack;
69 import net.pterodactylus.xdcc.data.Server;
71 import com.google.common.base.Optional;
72 import com.google.common.base.Predicate;
73 import com.google.common.collect.FluentIterable;
74 import com.google.common.collect.HashBasedTable;
75 import com.google.common.collect.HashMultimap;
76 import com.google.common.collect.ImmutableList;
77 import com.google.common.collect.ImmutableSet;
78 import com.google.common.collect.Lists;
79 import com.google.common.collect.Maps;
80 import com.google.common.collect.Multimap;
81 import com.google.common.collect.Sets;
82 import com.google.common.collect.Table;
83 import com.google.common.eventbus.EventBus;
84 import com.google.common.eventbus.Subscribe;
85 import com.google.common.io.Closeables;
86 import com.google.common.util.concurrent.AbstractExecutionThreadService;
87 import com.google.inject.Inject;
90 * The core of XDCC Downloader.
92 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
94 public class Core extends AbstractExecutionThreadService {
97 private static final Logger logger = Logger.getLogger(Core.class.getName());
100 private final EventBus eventBus;
102 /** The temporary directory to download files to. */
103 private final String temporaryDirectory;
105 /** The directory to move finished downloads to. */
106 private final String finalDirectory;
108 /** The channels that should be monitored. */
109 private final Collection<Channel> channels = Sets.newHashSet();
111 /** The channels that are currentlymonitored. */
112 private final Collection<Channel> joinedChannels = Sets.newHashSet();
114 /** The channels that are joined but not configured. */
115 private final Collection<Channel> extraChannels = Sets.newHashSet();
117 /** The current network connections. */
118 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
120 /** The currently known bots. */
121 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
123 /** The current downloads. */
124 private final Multimap<String, Download> downloads = HashMultimap.create();
126 /** The current DCC receivers. */
127 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
130 * Creates a new core.
134 * @param temporaryDirectory
135 * The directory to download files to
136 * @param finalDirectory
137 * The directory to move finished files to
140 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
141 this.eventBus = eventBus;
142 this.temporaryDirectory = temporaryDirectory;
143 this.finalDirectory = finalDirectory;
151 * Returns all currently known connections.
153 * @return All currently known connections
155 public Collection<Connection> connections() {
156 return networkConnections.values();
160 * Returns all configured channels. Due to various circumstances, configured
161 * channels might not actually be joined.
163 * @return All configured channels
165 public Collection<Channel> channels() {
166 return ImmutableSet.copyOf(channels);
170 * Returns all currently joined channels.
172 * @return All currently joined channels
174 public Collection<Channel> joinedChannels() {
175 return ImmutableSet.copyOf(joinedChannels);
179 * Returns all currently joined channels that are not configured.
181 * @return All currently joined but not configured channels
183 public Collection<Channel> extraChannels() {
184 return ImmutableSet.copyOf(extraChannels);
188 * Returns all currently known bots.
190 * @return All currently known bots
192 public Collection<Bot> bots() {
193 return networkBots.values();
197 * Returns all currently running downloads.
199 * @return All currently running downloads
201 public Collection<Download> downloads() {
202 return downloads.values();
210 * Adds a channel to monitor.
213 * The channel to monitor
215 public void addChannel(Channel channel) {
216 channels.add(channel);
220 * Fetches the given pack from the given bot.
223 * The bot to fetch the pack from
227 public void fetch(Bot bot, Pack pack) {
228 Connection connection = networkConnections.get(bot.network());
229 if (connection == null) {
233 /* check if we are already downloading the file? */
234 if (downloads.containsKey(pack.name())) {
235 Collection<Download> packDownloads = downloads.get(pack.name());
236 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
237 if (!runningDownloads.isEmpty()) {
238 Download download = runningDownloads.iterator().next();
239 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
242 StringBuilder bots = new StringBuilder();
243 for (Download download : packDownloads) {
244 if (bots.length() > 0) {
247 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
249 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
252 Download download = new Download(bot, pack);
253 downloads.put(pack.name(), download);
256 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
257 } catch (IOException ioe1) {
258 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
263 * Closes the given connection.
266 * The connection to close
268 public void closeConnection(Connection connection) {
271 } catch (IOException ioe1) {
277 // ABSTRACTIDLESERVICE METHODS
281 protected void startUp() {
282 for (Channel channel : channels) {
283 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
284 connectNetwork(channel.network());
287 /* notify listeners. */
288 eventBus.post(new CoreStarted(this));
292 protected void run() throws Exception {
293 while (isRunning()) {
295 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
296 } catch (InterruptedException ie1) {
300 /* find channels that should be monitored but are not. */
301 for (Channel channel : channels) {
302 if (joinedChannels.contains(channel)) {
306 connectNetwork(channel.network());
307 Connection connection = networkConnections.get(channel.network());
308 if (connection.established()) {
309 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
310 connection.joinChannel(channel.name());
317 protected void shutDown() {
325 * Starts a new connection for the given network if no such connection exists
329 * The network to connect to
331 private void connectNetwork(Network network) {
332 if (!networkConnections.containsKey(network)) {
333 /* select a random server. */
334 List<Server> servers = Lists.newArrayList(network.servers());
335 if (servers.isEmpty()) {
336 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
339 Server server = servers.get((int) (Math.random() * servers.size()));
340 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
341 connection.username(RandomNickname.get()).realName(RandomNickname.get());
342 networkConnections.put(network, connection);
348 * Removes the given connection and all its channels and bots.
351 * The connection to remove
353 private void removeConnection(Connection connection) {
354 Optional<Network> network = getNetwork(connection);
355 if (!network.isPresent()) {
359 /* find all channels that need to be removed. */
360 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
361 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
362 Channel joinedChannel = channelIterator.next();
363 if (!joinedChannel.network().equals(network.get())) {
367 channelIterator.remove();
371 /* now remove all bots for that network. */
372 Map<String, Bot> bots = networkBots.row(network.get());
373 int botCount = bots.size();
375 for (Bot bot : bots.values()) {
376 packCount += bot.packs().size();
379 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
381 /* now remove the network. */
382 networkConnections.remove(network.get());
390 * If a connection to a network has been established, the channels associated
391 * with this network are joined.
393 * @param connectionEstablished
394 * The connection established event
397 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
399 /* get network for connection. */
400 Optional<Network> network = getNetwork(connectionEstablished.connection());
403 if (!network.isPresent()) {
407 /* join all channels on this network. */
408 for (Channel channel : channels) {
409 if (channel.network().equals(network.get())) {
411 connectionEstablished.connection().joinChannel(channel.name());
412 } catch (IOException ioe1) {
413 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
420 * Remove all data stored for a network if the connection is closed.
422 * @param connectionClosed
423 * The connection closed event
426 public void connectionClosed(ConnectionClosed connectionClosed) {
427 removeConnection(connectionClosed.connection());
431 * Remove all data stored for a network if the connection fails.
433 * @param connectionFailed
434 * The connection failed event
436 public void connectionFailed(ConnectionFailed connectionFailed) {
437 removeConnection(connectionFailed.connection());
441 * Shows a message when a channel was joined by us.
443 * @param channelJoined
444 * The channel joined event
447 public void channelJoined(ChannelJoined channelJoined) {
448 if (channelJoined.connection().isSource(channelJoined.client())) {
449 Optional<Network> network = getNetwork(channelJoined.connection());
450 if (!network.isPresent()) {
454 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
455 if (!channel.isPresent()) {
456 /* it’s an extra channel. */
457 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
458 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
462 joinedChannels.add(channel.get());
463 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
468 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
471 * The channel left event
474 public void channelLeft(ChannelLeft channelLeft) {
475 Optional<Network> network = getNetwork(channelLeft.connection());
476 if (!network.isPresent()) {
480 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
482 /* maybe it was us? */
483 if (channelLeft.connection().isSource(channelLeft.client())) {
484 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
485 if (!channel.isPresent()) {
486 /* maybe it was an extra channel? */
487 channel = getExtraChannel(network.get(), channelLeft.channel());
488 if (!channel.isPresent()) {
489 /* okay, whatever. */
493 extraChannels.remove(channel);
495 channels.remove(channel.get());
498 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
504 Bot removedBot = networkBots.remove(network.get(), channelLeft.client().nick().get());
505 if (removedBot != null) {
506 eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
511 * Removes a client (which may be a bot) from the table of known bots.
514 * The client quit event
517 public void clientQuit(ClientQuit clientQuit) {
518 Optional<Network> network = getNetwork(clientQuit.connection());
519 if (!network.isPresent()) {
523 Bot removedBot = networkBots.remove(network.get(), clientQuit.client().nick().get());
524 if (removedBot != null) {
525 eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
530 * If the nickname of a bit changes, remove it from the old name and store it
531 * under the new name.
533 * @param nicknameChanged
534 * The nickname changed event
537 public void nicknameChanged(NicknameChanged nicknameChanged) {
538 Optional<Network> network = getNetwork(nicknameChanged.connection());
539 if (!network.isPresent()) {
543 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
548 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
552 * If a message on a channel is received, it is parsed for pack information
553 * with is then added to a bot.
555 * @param channelMessageReceived
556 * The channel message received event
559 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
560 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
561 if (!message.startsWith("#")) {
562 /* most probably not a pack announcement. */
566 Optional<Network> network = getNetwork(channelMessageReceived.connection());
567 if (!network.isPresent()) {
568 /* message for unknown connection? */
572 /* parse pack information. */
573 Optional<Pack> pack = parsePack(message);
574 if (!pack.isPresent()) {
579 synchronized (networkBots) {
580 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
581 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
582 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
583 eventBus.post(new BotAdded(bot));
585 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
590 bot.addPack(pack.get());
591 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
595 * Forward all private messages to every console.
597 * @param privateMessageReceived
598 * The private message recevied event
601 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
602 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
606 * Sends a message to all console when a notice was received.
608 * @param privateNoticeReceived
609 * The notice received event
612 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
613 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
614 if (!network.isPresent()) {
618 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.reply().source().get(), network.get(), privateNoticeReceived.text())));
622 * Starts a DCC download.
624 * @param dccSendReceived
628 public void dccSendReceived(final DccSendReceived dccSendReceived) {
629 final Optional<Network> network = getNetwork(dccSendReceived.connection());
630 if (!network.isPresent()) {
634 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
635 if (packDownloads.isEmpty()) {
636 /* unknown download, ignore. */
640 /* check if it’s already downloading. */
641 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
642 if (!runningDownloads.isEmpty()) {
643 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
647 /* locate the correct download. */
648 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
651 public boolean apply(Download download) {
652 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
656 /* we did not request this download. */
657 if (requestedDownload.isEmpty()) {
661 Download download = requestedDownload.iterator().next();
663 /* check if the file already exists. */
664 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
665 if (outputFile.exists()) {
666 long existingFileSize = outputFile.length();
668 /* file already complete? */
669 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
670 /* file is apparently already complete. just move it. */
671 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
672 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
674 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
677 /* remove download. */
678 downloads.removeAll(download.pack().name());
682 /* file not complete yet, DCC resume it. */
684 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
685 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
686 } catch (IOException ioe1) {
687 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
693 /* file does not exist, start the download. */
695 OutputStream fileOutputStream = new FileOutputStream(outputFile);
696 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
697 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
698 dccReceivers.add(dccReceiver);
700 eventBus.post(new DownloadStarted(download));
701 } catch (FileNotFoundException fnfe1) {
702 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
707 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
708 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
709 if (!network.isPresent()) {
713 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
714 if (packDownloads.isEmpty()) {
715 /* unknown download, ignore. */
719 /* check if it’s already downloading. */
720 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
721 if (!runningDownloads.isEmpty()) {
722 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
726 /* locate the correct download. */
727 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
730 public boolean apply(Download download) {
731 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
735 /* we did not request this download. */
736 if (requestedDownload.isEmpty()) {
740 Download download = requestedDownload.iterator().next();
743 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
744 if (outputFile.length() != dccAcceptReceived.position()) {
745 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
746 logger.log(Level.WARNING, String.format("Download %s from %s: have %d bytes but wants to resume from %d!", dccAcceptReceived.filename(), dccAcceptReceived.source(), outputFile.length(), dccAcceptReceived.position()));
748 downloads.removeAll(download.pack().name());
751 OutputStream outputStream = new FileOutputStream(outputFile, true);
752 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
753 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
754 dccReceivers.add(dccReceiver);
756 eventBus.post(new DownloadStarted(download));
757 } catch (FileNotFoundException fnfe1) {
762 * Closes the output stream of the download and moves the file to the final
765 * @param dccDownloadFinished
766 * The DCC download finished event
769 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
771 /* locate the correct download. */
772 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
773 if (requestedDownload.isEmpty()) {
774 /* this seems wrong. */
775 logger.warning("Download finished but could not be located.");
778 Download download = requestedDownload.iterator().next();
781 download.outputStream().close();
782 File file = new File(download.filename());
783 file.renameTo(new File(finalDirectory, download.pack().name()));
784 eventBus.post(new DownloadFinished(download));
785 dccReceivers.remove(dccDownloadFinished.dccReceiver());
786 downloads.removeAll(download.pack().name());
787 } catch (IOException ioe1) {
788 /* TODO - handle all the errors. */
789 logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
794 * Closes the output stream and notifies all listeners of the failure.
796 * @param dccDownloadFailed
797 * The DCC download failed event
800 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
802 /* locate the correct download. */
803 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
804 if (requestedDownload.isEmpty()) {
805 /* this seems wrong. */
806 logger.warning("Download finished but could not be located.");
809 Download download = requestedDownload.iterator().next();
812 Closeables.close(download.outputStream(), true);
813 eventBus.post(new DownloadFailed(download));
814 dccReceivers.remove(dccDownloadFailed.dccReceiver());
815 downloads.removeAll(download.pack().name());
816 } catch (IOException ioe1) {
817 /* swallow silently. */
826 * Searches all current connections for the given connection, returning the
827 * associated network.
830 * The connection to get the network for
831 * @return The network belonging to the connection, or {@link
834 private Optional<Network> getNetwork(Connection connection) {
835 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
836 if (networkConnectionEntry.getValue().equals(connection)) {
837 return Optional.of(networkConnectionEntry.getKey());
840 return Optional.absent();
844 * Returns the configured channel for the given network and name.
847 * The network the channel is located on
849 * The name of the channel
850 * @return The configured channel, or {@link Optional#absent()} if no
851 * configured channel matching the given network and name was found
853 public Optional<Channel> getChannel(Network network, String channelName) {
854 for (Channel channel : channels) {
855 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
856 return Optional.of(channel);
859 return Optional.absent();
863 * Returns the extra channel for the given network and name.
866 * The network the channel is located on
868 * The name of the channel
869 * @return The extra channel, or {@link Optional#absent()} if no extra channel
870 * matching the given network and name was found
872 public Optional<Channel> getExtraChannel(Network network, String channelName) {
873 for (Channel channel : extraChannels) {
874 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
875 return Optional.of(channel);
878 return Optional.absent();
882 * Parses {@link Pack} information from the given message.
885 * The message to parse pack information from
886 * @return The parsed pack, or {@link Optional#absent()} if the message could
887 * not be parsed into a pack
889 private Optional<Pack> parsePack(String message) {
890 int squareOpen = message.indexOf('[');
891 int squareClose = message.indexOf(']', squareOpen);
892 if ((squareOpen == -1) && (squareClose == -1)) {
893 return Optional.absent();
895 String packSize = message.substring(squareOpen + 1, squareClose);
896 String packName = message.substring(message.lastIndexOf(' ') + 1);
897 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
898 return Optional.of(new Pack(packIndex, packSize, packName));