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.DccAcceptReceived;
47 import net.pterodactylus.irc.event.DccDownloadFailed;
48 import net.pterodactylus.irc.event.DccDownloadFinished;
49 import net.pterodactylus.irc.event.DccSendReceived;
50 import net.pterodactylus.irc.event.NicknameChanged;
51 import net.pterodactylus.irc.event.PrivateMessageReceived;
52 import net.pterodactylus.irc.event.PrivateNoticeReceived;
53 import net.pterodactylus.irc.util.MessageCleaner;
54 import net.pterodactylus.irc.util.RandomNickname;
55 import net.pterodactylus.xdcc.core.event.BotAdded;
56 import net.pterodactylus.xdcc.core.event.CoreStarted;
57 import net.pterodactylus.xdcc.core.event.DownloadFailed;
58 import net.pterodactylus.xdcc.core.event.DownloadFinished;
59 import net.pterodactylus.xdcc.core.event.DownloadStarted;
60 import net.pterodactylus.xdcc.core.event.GenericError;
61 import net.pterodactylus.xdcc.core.event.GenericMessage;
62 import net.pterodactylus.xdcc.core.event.MessageReceived;
63 import net.pterodactylus.xdcc.data.Bot;
64 import net.pterodactylus.xdcc.data.Channel;
65 import net.pterodactylus.xdcc.data.Download;
66 import net.pterodactylus.xdcc.data.Network;
67 import net.pterodactylus.xdcc.data.Pack;
68 import net.pterodactylus.xdcc.data.Server;
70 import com.google.common.base.Optional;
71 import com.google.common.base.Predicate;
72 import com.google.common.collect.FluentIterable;
73 import com.google.common.collect.HashBasedTable;
74 import com.google.common.collect.HashMultimap;
75 import com.google.common.collect.ImmutableList;
76 import com.google.common.collect.ImmutableSet;
77 import com.google.common.collect.Lists;
78 import com.google.common.collect.Maps;
79 import com.google.common.collect.Multimap;
80 import com.google.common.collect.Sets;
81 import com.google.common.collect.Table;
82 import com.google.common.eventbus.EventBus;
83 import com.google.common.eventbus.Subscribe;
84 import com.google.common.io.Closeables;
85 import com.google.common.util.concurrent.AbstractExecutionThreadService;
86 import com.google.inject.Inject;
89 * The core of XDCC Downloader.
91 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
93 public class Core extends AbstractExecutionThreadService {
96 private static final Logger logger = Logger.getLogger(Core.class.getName());
99 private final EventBus eventBus;
101 /** The temporary directory to download files to. */
102 private final String temporaryDirectory;
104 /** The directory to move finished downloads to. */
105 private final String finalDirectory;
107 /** The channels that should be monitored. */
108 private final Collection<Channel> channels = Sets.newHashSet();
110 /** The channels that are currentlymonitored. */
111 private final Collection<Channel> joinedChannels = Sets.newHashSet();
113 /** The channels that are joined but not configured. */
114 private final Collection<Channel> extraChannels = Sets.newHashSet();
116 /** The current network connections. */
117 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
119 /** The currently known bots. */
120 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
122 /** The current downloads. */
123 private final Multimap<String, Download> downloads = HashMultimap.create();
125 /** The current DCC receivers. */
126 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
129 * Creates a new core.
133 * @param temporaryDirectory
134 * The directory to download files to
135 * @param finalDirectory
136 * The directory to move finished files to
139 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
140 this.eventBus = eventBus;
141 this.temporaryDirectory = temporaryDirectory;
142 this.finalDirectory = finalDirectory;
150 * Returns all configured channels. Due to various circumstances, configured
151 * channels might not actually be joined.
153 * @return All configured channels
155 public Collection<Channel> channels() {
156 return ImmutableSet.copyOf(channels);
160 * Returns all currently joined channels.
162 * @return All currently joined channels
164 public Collection<Channel> joinedChannels() {
165 return ImmutableSet.copyOf(joinedChannels);
169 * Returns all currently joined channels that are not configured.
171 * @return All currently joined but not configured channels
173 public Collection<Channel> extraChannels() {
174 return ImmutableSet.copyOf(extraChannels);
178 * Returns all currently known bots.
180 * @return All currently known bots
182 public Collection<Bot> bots() {
183 return networkBots.values();
187 * Returns all currently running downloads.
189 * @return All currently running downloads
191 public Collection<Download> downloads() {
192 return downloads.values();
200 * Adds a channel to monitor.
203 * The channel to monitor
205 public void addChannel(Channel channel) {
206 channels.add(channel);
210 * Fetches the given pack from the given bot.
213 * The bot to fetch the pack from
217 public void fetch(Bot bot, Pack pack) {
218 Connection connection = networkConnections.get(bot.network());
219 if (connection == null) {
223 /* check if we are already downloading the file? */
224 if (downloads.containsKey(pack.name())) {
225 Collection<Download> packDownloads = downloads.get(pack.name());
226 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
227 if (!runningDownloads.isEmpty()) {
228 Download download = runningDownloads.iterator().next();
229 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
232 StringBuilder bots = new StringBuilder();
233 for (Download download : packDownloads) {
234 if (bots.length() > 0) {
237 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
239 eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
242 Download download = new Download(bot, pack);
243 downloads.put(pack.name(), download);
246 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
247 } catch (IOException ioe1) {
248 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
253 * Closes the given connection.
256 * The connection to close
258 public void closeConnection(Connection connection) {
261 } catch (IOException ioe1) {
267 // ABSTRACTIDLESERVICE METHODS
271 protected void startUp() {
272 for (Channel channel : channels) {
273 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
274 connectNetwork(channel.network());
277 /* notify listeners. */
278 eventBus.post(new CoreStarted(this));
282 protected void run() throws Exception {
283 while (isRunning()) {
285 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
286 } catch (InterruptedException ie1) {
290 /* find channels that should be monitored but are not. */
291 for (Channel channel : channels) {
292 if (joinedChannels.contains(channel)) {
296 connectNetwork(channel.network());
297 Connection connection = networkConnections.get(channel.network());
298 if (connection.established()) {
299 eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
300 connection.joinChannel(channel.name());
307 protected void shutDown() {
315 * Starts a new connection for the given network if no such connection exists
319 * The network to connect to
321 private void connectNetwork(Network network) {
322 if (!networkConnections.containsKey(network)) {
323 /* select a random server. */
324 List<Server> servers = Lists.newArrayList(network.servers());
325 if (servers.isEmpty()) {
326 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
329 Server server = servers.get((int) (Math.random() * servers.size()));
330 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
331 connection.username(RandomNickname.get()).realName(RandomNickname.get());
332 networkConnections.put(network, connection);
342 * If a connection to a network has been established, the channels associated
343 * with this network are joined.
345 * @param connectionEstablished
346 * The connection established event
349 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
351 /* get network for connection. */
352 Optional<Network> network = getNetwork(connectionEstablished.connection());
355 if (!network.isPresent()) {
359 /* join all channels on this network. */
360 for (Channel channel : channels) {
361 if (channel.network().equals(network.get())) {
363 connectionEstablished.connection().joinChannel(channel.name());
364 } catch (IOException ioe1) {
365 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
372 * Remove all data stored for a network if the connection is closed.
374 * @param connectionClosed
375 * The connection closed event
378 public void connectionClosed(ConnectionClosed connectionClosed) {
379 Optional<Network> network = getNetwork(connectionClosed.connection());
380 if (!network.isPresent()) {
384 /* find all channels that need to be removed. */
385 for (Collection channels : ImmutableList.of(joinedChannels, extraChannels)) {
386 for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
387 Channel joinedChannel = channelIterator.next();
388 if (!joinedChannel.network().equals(network.get())) {
392 channelIterator.remove();
396 /* now remove all bots for that network. */
397 Map<String, Bot> bots = networkBots.row(network.get());
398 int botCount = bots.size();
400 for (Bot bot : bots.values()) {
401 packCount += bot.packs().size();
404 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
406 /* now remove the network. */
407 networkConnections.remove(network.get());
411 * Shows a message when a channel was joined by us.
413 * @param channelJoined
414 * The channel joined event
417 public void channelJoined(ChannelJoined channelJoined) {
418 if (channelJoined.connection().isSource(channelJoined.client())) {
419 Optional<Network> network = getNetwork(channelJoined.connection());
420 if (!network.isPresent()) {
424 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
425 if (!channel.isPresent()) {
426 /* it’s an extra channel. */
427 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
428 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
432 joinedChannels.add(channel.get());
433 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
438 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
441 * The channel left event
444 public void channelLeft(ChannelLeft channelLeft) {
445 Optional<Network> network = getNetwork(channelLeft.connection());
446 if (!network.isPresent()) {
450 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
452 /* maybe it was us? */
453 if (channelLeft.connection().isSource(channelLeft.client())) {
454 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
455 if (!channel.isPresent()) {
456 /* maybe it was an extra channel? */
457 channel = getExtraChannel(network.get(), channelLeft.channel());
458 if (!channel.isPresent()) {
459 /* okay, whatever. */
463 extraChannels.remove(channel);
465 channels.remove(channel.get());
468 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
474 Bot removedBot = networkBots.remove(network.get(), channelLeft.client().nick().get());
475 if (removedBot != null) {
476 eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
481 * Removes a client (which may be a bot) from the table of known bots.
484 * The client quit event
487 public void clientQuit(ClientQuit clientQuit) {
488 Optional<Network> network = getNetwork(clientQuit.connection());
489 if (!network.isPresent()) {
493 Bot removedBot = networkBots.remove(network.get(), clientQuit.client().nick().get());
494 if (removedBot != null) {
495 eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
500 * If the nickname of a bit changes, remove it from the old name and store it
501 * under the new name.
503 * @param nicknameChanged
504 * The nickname changed event
507 public void nicknameChanged(NicknameChanged nicknameChanged) {
508 Optional<Network> network = getNetwork(nicknameChanged.connection());
509 if (!network.isPresent()) {
513 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
518 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
522 * If a message on a channel is received, it is parsed for pack information
523 * with is then added to a bot.
525 * @param channelMessageReceived
526 * The channel message received event
529 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
530 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
531 if (!message.startsWith("#")) {
532 /* most probably not a pack announcement. */
536 Optional<Network> network = getNetwork(channelMessageReceived.connection());
537 if (!network.isPresent()) {
538 /* message for unknown connection? */
542 /* parse pack information. */
543 Optional<Pack> pack = parsePack(message);
544 if (!pack.isPresent()) {
549 synchronized (networkBots) {
550 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
551 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
552 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
553 eventBus.post(new BotAdded(bot));
555 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
560 bot.addPack(pack.get());
561 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
565 * Forward all private messages to every console.
567 * @param privateMessageReceived
568 * The private message recevied event
571 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
572 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
576 * Sends a message to all console when a notice was received.
578 * @param privateNoticeReceived
579 * The notice received event
582 public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
583 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
584 if (!network.isPresent()) {
588 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.reply().source().get(), network.get(), privateNoticeReceived.text())));
592 * Starts a DCC download.
594 * @param dccSendReceived
598 public void dccSendReceived(final DccSendReceived dccSendReceived) {
599 final Optional<Network> network = getNetwork(dccSendReceived.connection());
600 if (!network.isPresent()) {
604 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
605 if (packDownloads.isEmpty()) {
606 /* unknown download, ignore. */
610 /* check if it’s already downloading. */
611 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
612 if (!runningDownloads.isEmpty()) {
613 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
617 /* locate the correct download. */
618 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
621 public boolean apply(Download download) {
622 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
626 /* we did not request this download. */
627 if (requestedDownload.isEmpty()) {
631 Download download = requestedDownload.iterator().next();
633 /* check if the file already exists. */
634 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
635 if (outputFile.exists()) {
636 long existingFileSize = outputFile.length();
638 /* file already complete? */
639 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
640 /* file is apparently already complete. just move it. */
641 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
642 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
644 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
647 /* remove download. */
648 downloads.removeAll(download.pack().name());
652 /* file not complete yet, DCC resume it. */
654 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
655 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
656 } catch (IOException ioe1) {
657 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
663 /* file does not exist, start the download. */
665 OutputStream fileOutputStream = new FileOutputStream(outputFile);
666 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
667 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
668 dccReceivers.add(dccReceiver);
670 eventBus.post(new DownloadStarted(download));
671 } catch (FileNotFoundException fnfe1) {
672 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
677 public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
678 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
679 if (!network.isPresent()) {
683 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
684 if (packDownloads.isEmpty()) {
685 /* unknown download, ignore. */
689 /* check if it’s already downloading. */
690 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
691 if (!runningDownloads.isEmpty()) {
692 eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
696 /* locate the correct download. */
697 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
700 public boolean apply(Download download) {
701 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
705 /* we did not request this download. */
706 if (requestedDownload.isEmpty()) {
710 Download download = requestedDownload.iterator().next();
713 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
714 if (outputFile.length() != dccAcceptReceived.position()) {
715 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
716 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()));
718 downloads.removeAll(download.pack().name());
721 OutputStream outputStream = new FileOutputStream(outputFile, true);
722 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
723 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
724 dccReceivers.add(dccReceiver);
726 eventBus.post(new DownloadStarted(download));
727 } catch (FileNotFoundException fnfe1) {
732 * Closes the output stream of the download and moves the file to the final
735 * @param dccDownloadFinished
736 * The DCC download finished event
739 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
741 /* locate the correct download. */
742 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
743 if (requestedDownload.isEmpty()) {
744 /* this seems wrong. */
745 logger.warning("Download finished but could not be located.");
748 Download download = requestedDownload.iterator().next();
751 download.outputStream().close();
752 File file = new File(download.filename());
753 file.renameTo(new File(finalDirectory, download.pack().name()));
754 eventBus.post(new DownloadFinished(download));
755 dccReceivers.remove(dccDownloadFinished.dccReceiver());
756 downloads.removeAll(download.pack().name());
757 } catch (IOException ioe1) {
758 /* TODO - handle all the errors. */
759 logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
764 * Closes the output stream and notifies all listeners of the failure.
766 * @param dccDownloadFailed
767 * The DCC download failed event
770 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
772 /* locate the correct download. */
773 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
774 if (requestedDownload.isEmpty()) {
775 /* this seems wrong. */
776 logger.warning("Download finished but could not be located.");
779 Download download = requestedDownload.iterator().next();
782 Closeables.close(download.outputStream(), true);
783 eventBus.post(new DownloadFailed(download));
784 dccReceivers.remove(dccDownloadFailed.dccReceiver());
785 downloads.removeAll(download.pack().name());
786 } catch (IOException ioe1) {
787 /* swallow silently. */
796 * Searches all current connections for the given connection, returning the
797 * associated network.
800 * The connection to get the network for
801 * @return The network belonging to the connection, or {@link
804 private Optional<Network> getNetwork(Connection connection) {
805 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
806 if (networkConnectionEntry.getValue().equals(connection)) {
807 return Optional.of(networkConnectionEntry.getKey());
810 return Optional.absent();
814 * Returns the configured channel for the given network and name.
817 * The network the channel is located on
819 * The name of the channel
820 * @return The configured channel, or {@link Optional#absent()} if no
821 * configured channel matching the given network and name was found
823 public Optional<Channel> getChannel(Network network, String channelName) {
824 for (Channel channel : channels) {
825 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
826 return Optional.of(channel);
829 return Optional.absent();
833 * Returns the extra channel for the given network and name.
836 * The network the channel is located on
838 * The name of the channel
839 * @return The extra channel, or {@link Optional#absent()} if no extra channel
840 * matching the given network and name was found
842 public Optional<Channel> getExtraChannel(Network network, String channelName) {
843 for (Channel channel : extraChannels) {
844 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
845 return Optional.of(channel);
848 return Optional.absent();
852 * Parses {@link Pack} information from the given message.
855 * The message to parse pack information from
856 * @return The parsed pack, or {@link Optional#absent()} if the message could
857 * not be parsed into a pack
859 private Optional<Pack> parsePack(String message) {
860 int squareOpen = message.indexOf('[');
861 int squareClose = message.indexOf(']', squareOpen);
862 if ((squareOpen == -1) && (squareClose == -1)) {
863 return Optional.absent();
865 String packSize = message.substring(squareOpen + 1, squareClose);
866 String packName = message.substring(message.lastIndexOf(' ') + 1);
867 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
868 return Optional.of(new Pack(packIndex, packSize, packName));