Remove all network-related data if the network is disconnected.
[xudocci.git] / src / main / java / net / pterodactylus / xdcc / core / Core.java
1 /*
2  * XdccDownloader - Core.java - Copyright © 2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.xdcc.core;
19
20 import java.io.File;
21 import java.io.FileNotFoundException;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStream;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.concurrent.TimeUnit;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
34
35 import net.pterodactylus.irc.Connection;
36 import net.pterodactylus.irc.ConnectionBuilder;
37 import net.pterodactylus.irc.DccReceiver;
38 import net.pterodactylus.irc.event.ChannelJoined;
39 import net.pterodactylus.irc.event.ChannelLeft;
40 import net.pterodactylus.irc.event.ChannelMessageReceived;
41 import net.pterodactylus.irc.event.ClientQuit;
42 import net.pterodactylus.irc.event.ConnectionClosed;
43 import net.pterodactylus.irc.event.ConnectionEstablished;
44 import net.pterodactylus.irc.event.DccAcceptReceived;
45 import net.pterodactylus.irc.event.DccDownloadFailed;
46 import net.pterodactylus.irc.event.DccDownloadFinished;
47 import net.pterodactylus.irc.event.DccSendReceived;
48 import net.pterodactylus.irc.event.NicknameChanged;
49 import net.pterodactylus.irc.event.PrivateMessageReceived;
50 import net.pterodactylus.irc.util.MessageCleaner;
51 import net.pterodactylus.irc.util.RandomNickname;
52 import net.pterodactylus.xdcc.core.event.BotAdded;
53 import net.pterodactylus.xdcc.core.event.CoreStarted;
54 import net.pterodactylus.xdcc.core.event.DownloadFailed;
55 import net.pterodactylus.xdcc.core.event.DownloadFinished;
56 import net.pterodactylus.xdcc.core.event.DownloadStarted;
57 import net.pterodactylus.xdcc.core.event.GenericError;
58 import net.pterodactylus.xdcc.core.event.GenericMessage;
59 import net.pterodactylus.xdcc.core.event.MessageReceived;
60 import net.pterodactylus.xdcc.data.Bot;
61 import net.pterodactylus.xdcc.data.Channel;
62 import net.pterodactylus.xdcc.data.Download;
63 import net.pterodactylus.xdcc.data.Network;
64 import net.pterodactylus.xdcc.data.Pack;
65 import net.pterodactylus.xdcc.data.Server;
66
67 import com.google.common.base.Optional;
68 import com.google.common.collect.HashBasedTable;
69 import com.google.common.collect.ImmutableList;
70 import com.google.common.collect.ImmutableSet;
71 import com.google.common.collect.Lists;
72 import com.google.common.collect.Maps;
73 import com.google.common.collect.Sets;
74 import com.google.common.collect.Table;
75 import com.google.common.eventbus.EventBus;
76 import com.google.common.eventbus.Subscribe;
77 import com.google.common.io.Closeables;
78 import com.google.common.util.concurrent.AbstractExecutionThreadService;
79 import com.google.inject.Inject;
80
81 /**
82  * The core of XDCC Downloader.
83  *
84  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
85  */
86 public class Core extends AbstractExecutionThreadService {
87
88         /** The logger. */
89         private static final Logger logger = Logger.getLogger(Core.class.getName());
90
91         /** The event bus. */
92         private final EventBus eventBus;
93
94         /** The temporary directory to download files to. */
95         private final String temporaryDirectory;
96
97         /** The directory to move finished downloads to. */
98         private final String finalDirectory;
99
100         /** The channels that should be monitored. */
101         private final Collection<Channel> channels = Sets.newHashSet();
102
103         /** The channels that are currentlymonitored. */
104         private final Collection<Channel> joinedChannels = Sets.newHashSet();
105
106         /** The channels that are joined but not configured. */
107         private final Collection<Channel> extraChannels = Sets.newHashSet();
108
109         /** The current network connections. */
110         private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
111
112         /** The currently known bots. */
113         private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
114
115         /** The current downloads. */
116         private final Map<String, Download> downloads = Maps.newHashMap();
117
118         /** The current DCC receivers. */
119         private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
120
121         /**
122          * Creates a new core.
123          *
124          * @param eventBus
125          *              The event bus
126          * @param temporaryDirectory
127          *              The directory to download files to
128          * @param finalDirectory
129          *              The directory to move finished files to
130          */
131         @Inject
132         public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
133                 this.eventBus = eventBus;
134                 this.temporaryDirectory = temporaryDirectory;
135                 this.finalDirectory = finalDirectory;
136         }
137
138         //
139         // ACCESSORS
140         //
141
142         /**
143          * Returns all configured channels. Due to various circumstances, configured
144          * channels might not actually be joined.
145          *
146          * @return All configured channels
147          */
148         public Collection<Channel> channels() {
149                 return ImmutableSet.copyOf(channels);
150         }
151
152         /**
153          * Returns all currently joined channels.
154          *
155          * @return All currently joined channels
156          */
157         public Collection<Channel> joinedChannels() {
158                 return ImmutableSet.copyOf(joinedChannels);
159         }
160
161         /**
162          * Returns all currently joined channels that are not configured.
163          *
164          * @return All currently joined but not configured channels
165          */
166         public Collection<Channel> extraChannels() {
167                 return ImmutableSet.copyOf(extraChannels);
168         }
169
170         /**
171          * Returns all currently known bots.
172          *
173          * @return All currently known bots
174          */
175         public Collection<Bot> bots() {
176                 return networkBots.values();
177         }
178
179         /**
180          * Returns the currently active DCC receivers.
181          *
182          * @return The currently active DCC receivers
183          */
184         public Collection<DccReceiver> dccReceivers() {
185                 return dccReceivers;
186         }
187
188         //
189         // ACTIONS
190         //
191
192         /**
193          * Adds a channel to monitor.
194          *
195          * @param channel
196          *              The channel to monitor
197          */
198         public void addChannel(Channel channel) {
199                 channels.add(channel);
200         }
201
202         /**
203          * Fetches the given pack from the given bot.
204          *
205          * @param bot
206          *              The bot to fetch the pack from
207          * @param pack
208          *              The pack to fetch
209          */
210         public void fetch(Bot bot, Pack pack) {
211                 Connection connection = networkConnections.get(bot.network());
212                 if (connection == null) {
213                         return;
214                 }
215
216                 Download download = new Download(bot, pack);
217                 downloads.put(pack.name(), download);
218
219                 try {
220                         connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
221                 } catch (IOException ioe1) {
222                         logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
223                 }
224         }
225
226         //
227         // ABSTRACTIDLESERVICE METHODS
228         //
229
230         @Override
231         protected void startUp() {
232                 for (Channel channel : channels) {
233                         logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
234                         connectNetwork(channel.network());
235                 }
236
237                 /* notify listeners. */
238                 eventBus.post(new CoreStarted(this));
239         }
240
241         @Override
242         protected void run() throws Exception {
243                 while (isRunning()) {
244                         try {
245                                 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
246                         } catch (InterruptedException ie1) {
247                                 /* ignore. */
248                         }
249
250                         /* find channels that should be monitored but are not. */
251                         for (Channel channel : channels) {
252                                 if (joinedChannels.contains(channel)) {
253                                         continue;
254                                 }
255
256                                 connectNetwork(channel.network());
257                                 Connection connection = networkConnections.get(channel.network());
258                                 if (connection.established()) {
259                                         eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
260                                         connection.joinChannel(channel.name());
261                                 }
262                         }
263                 }
264         }
265
266         @Override
267         protected void shutDown() {
268         }
269
270         //
271         // PRIVATE METHODS
272         //
273
274         /**
275          * Starts a new connection for the given network if no such connection exists
276          * already.
277          *
278          * @param network
279          *              The network to connect to
280          */
281         private void connectNetwork(Network network) {
282                 if (!networkConnections.containsKey(network)) {
283                                 /* select a random server. */
284                         List<Server> servers = Lists.newArrayList(network.servers());
285                         if (servers.isEmpty()) {
286                                 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
287                                 return;
288                         }
289                         Server server = servers.get((int) (Math.random() * servers.size()));
290                         Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
291                         connection.username(RandomNickname.get()).realName(RandomNickname.get());
292                         networkConnections.put(network, connection);
293                         connection.start();
294                 }
295         }
296
297         //
298         // EVENT HANDLERS
299         //
300
301         /**
302          * If a connection to a network has been established, the channels associated
303          * with this network are joined.
304          *
305          * @param connectionEstablished
306          *              The connection established event
307          */
308         @Subscribe
309         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
310
311                 /* get network for connection. */
312                 Optional<Network> network = getNetwork(connectionEstablished.connection());
313
314                 /* found network? */
315                 if (!network.isPresent()) {
316                         return;
317                 }
318
319                 /* join all channels on this network. */
320                 for (Channel channel : channels) {
321                         if (channel.network().equals(network.get())) {
322                                 try {
323                                         connectionEstablished.connection().joinChannel(channel.name());
324                                 } catch (IOException ioe1) {
325                                         logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
326                                 }
327                         }
328                 }
329         }
330
331         /**
332          * Remove all data stored for a network if the connection is closed.
333          *
334          * @param connectionClosed
335          *              The connection closed event
336          */
337         @Subscribe
338         public void connectionClosed(ConnectionClosed connectionClosed) {
339                 Optional<Network> network = getNetwork(connectionClosed.connection());
340                 if (!network.isPresent()) {
341                         return;
342                 }
343
344                 /* find all channels that need to be removed. */
345                 for (Collection channels : ImmutableList.of(joinedChannels, extraChannels)) {
346                         for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
347                                 Channel joinedChannel = channelIterator.next();
348                                 if (!joinedChannel.network().equals(network.get())) {
349                                         continue;
350                                 }
351
352                                 channelIterator.remove();
353                         }
354                 }
355
356                 /* now remove all bots for that network. */
357                 Map<String, Bot> bots = networkBots.row(network.get());
358                 int botCount = bots.size();
359                 int packCount = 0;
360                 for (Bot bot : bots.values()) {
361                         packCount += bot.packs().size();
362                 }
363                 bots.clear();
364                 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
365
366                 /* now remove the network. */
367                 networkConnections.remove(network.get());
368         }
369
370         /**
371          * Shows a message when a channel was joined by us.
372          *
373          * @param channelJoined
374          *              The channel joined event
375          */
376         @Subscribe
377         public void channelJoined(ChannelJoined channelJoined) {
378                 if (channelJoined.connection().isSource(channelJoined.client())) {
379                         Optional<Network> network = getNetwork(channelJoined.connection());
380                         if (!network.isPresent()) {
381                                 return;
382                         }
383
384                         Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
385                         if (!channel.isPresent()) {
386                                 /* it’s an extra channel. */
387                                 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
388                                 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
389                                 return;
390                         }
391
392                         joinedChannels.add(channel.get());
393                         logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
394                 }
395         }
396
397         /**
398          * Removes bots that leave a channel, or channels when it’s us that’s leaving.
399          *
400          * @param channelLeft
401          *              The channel left event
402          */
403         @Subscribe
404         public void channelLeft(ChannelLeft channelLeft) {
405                 Optional<Network> network = getNetwork(channelLeft.connection());
406                 if (!network.isPresent()) {
407                         return;
408                 }
409
410                 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
411                 if (bot == null) {
412                         /* maybe it was us? */
413                         if (channelLeft.connection().isSource(channelLeft.client())) {
414                                 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
415                                 if (!channel.isPresent()) {
416                                         /* maybe it was an extra channel? */
417                                         channel = getExtraChannel(network.get(), channelLeft.channel());
418                                         if (!channel.isPresent()) {
419                                                 /* okay, whatever. */
420                                                 return;
421                                         }
422
423                                         extraChannels.remove(channel);
424                                 } else {
425                                         channels.remove(channel.get());
426                                 }
427
428                                 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
429                         }
430
431                         return;
432                 }
433
434                 Bot removedBot = networkBots.remove(network.get(), channelLeft.client().nick().get());
435                 if (removedBot != null) {
436                         eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
437                 }
438         }
439
440         /**
441          * Removes a client (which may be a bot) from the table of known bots.
442          *
443          * @param clientQuit
444          *              The client quit event
445          */
446         @Subscribe
447         public void clientQuit(ClientQuit clientQuit) {
448                 Optional<Network> network = getNetwork(clientQuit.connection());
449                 if (!network.isPresent()) {
450                         return;
451                 }
452
453                 Bot removedBot = networkBots.remove(network.get(), clientQuit.client().nick().get());
454                 if (removedBot != null) {
455                         eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
456                 }
457         }
458
459         /**
460          * If the nickname of a bit changes, remove it from the old name and store it
461          * under the new name.
462          *
463          * @param nicknameChanged
464          *              The nickname changed event
465          */
466         @Subscribe
467         public void nicknameChanged(NicknameChanged nicknameChanged) {
468                 Optional<Network> network = getNetwork(nicknameChanged.connection());
469                 if (!network.isPresent()) {
470                         return;
471                 }
472
473                 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
474                 if (bot == null) {
475                         return;
476                 }
477
478                 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
479         }
480
481         /**
482          * If a message on a channel is received, it is parsed for pack information
483          * with is then added to a bot.
484          *
485          * @param channelMessageReceived
486          *              The channel message received event
487          */
488         @Subscribe
489         public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
490                 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
491                 if (!message.startsWith("#")) {
492                         /* most probably not a pack announcement. */
493                         return;
494                 }
495
496                 Optional<Network> network = getNetwork(channelMessageReceived.connection());
497                 if (!network.isPresent()) {
498                         /* message for unknown connection? */
499                         return;
500                 }
501
502                 /* parse pack information. */
503                 Optional<Pack> pack = parsePack(message);
504                 if (!pack.isPresent()) {
505                         return;
506                 }
507
508                 Bot bot;
509                 synchronized (networkBots) {
510                         if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
511                                 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
512                                 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
513                                 eventBus.post(new BotAdded(bot));
514                         } else {
515                                 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
516                         }
517                 }
518
519                 /* add pack. */
520                 bot.addPack(pack.get());
521                 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
522         }
523
524         /**
525          * Forward all private messages to every console.
526          *
527          * @param privateMessageReceived
528          *              The private message recevied event
529          */
530         @Subscribe
531         public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
532                 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
533         }
534
535         /**
536          * Starts a DCC download.
537          *
538          * @param dccSendReceived
539          *              The DCC SEND event
540          */
541         @Subscribe
542         public void dccSendReceived(DccSendReceived dccSendReceived) {
543                 Optional<Network> network = getNetwork(dccSendReceived.connection());
544                 if (!network.isPresent()) {
545                         return;
546                 }
547
548                 Download download = downloads.get(dccSendReceived.filename());
549                 if (download == null) {
550                         /* unknown download, ignore. */
551                         return;
552                 }
553
554                 /* check if the file already exists. */
555                 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
556                 if (outputFile.exists()) {
557                         long existingFileSize = outputFile.length();
558
559                         /* file already complete? */
560                         if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
561                                 /* file is apparently already complete. just move it. */
562                                 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
563                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
564                                 } else {
565                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
566                                 }
567
568                                 /* remove download. */
569                                 downloads.remove(download);
570                                 return;
571                         }
572
573                         /* file not complete yet, DCC resume it. */
574                         try {
575                                 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
576                                 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
577                         } catch (IOException ioe1) {
578                                 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
579                         }
580
581                         return;
582                 }
583
584                 /* file does not exist, start the download. */
585                 try {
586                         OutputStream fileOutputStream = new FileOutputStream(outputFile);
587                         DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
588                         download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
589                         dccReceivers.add(dccReceiver);
590                         dccReceiver.start();
591                         eventBus.post(new DownloadStarted(download));
592                 } catch (FileNotFoundException fnfe1) {
593                         eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
594                 }
595         }
596
597         @Subscribe
598         public void dccAcceptReceived(DccAcceptReceived dccAcceptReceived) {
599                 Optional<Network> network = getNetwork(dccAcceptReceived.connection());
600                 if (!network.isPresent()) {
601                         return;
602                 }
603
604                 Download download = downloads.get(dccAcceptReceived.filename());
605                 if (download == null) {
606                         /* unknown download, ignore. */
607                         return;
608                 }
609
610                 try {
611                         File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
612                         if (outputFile.length() != dccAcceptReceived.position()) {
613                                 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
614                                 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()));
615
616                                 downloads.remove(download);
617                                 return;
618                         }
619                         OutputStream outputStream = new FileOutputStream(outputFile, true);
620                         DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
621                         download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
622                         dccReceivers.add(dccReceiver);
623                         dccReceiver.start();
624                         eventBus.post(new DownloadStarted(download));
625                 } catch (FileNotFoundException fnfe1) {
626                 }
627         }
628
629         /**
630          * Closes the output stream of the download and moves the file to the final
631          * location.
632          *
633          * @param dccDownloadFinished
634          *              The DCC download finished event
635          */
636         @Subscribe
637         public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
638                 Download download = downloads.get(dccDownloadFinished.dccReceiver().filename());
639                 if (download == null) {
640                         /* probably shouldn’t happen. */
641                         return;
642                 }
643
644                 try {
645                         download.outputStream().close();
646                         File file = new File(download.filename());
647                         file.renameTo(new File(finalDirectory, download.pack().name()));
648                         eventBus.post(new DownloadFinished(download));
649                         dccReceivers.remove(dccDownloadFinished.dccReceiver());
650                         downloads.remove(download);
651                 } catch (IOException ioe1) {
652                         /* TODO - handle all the errors. */
653                         logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
654                 }
655         }
656
657         /**
658          * Closes the output stream and notifies all listeners of the failure.
659          *
660          * @param dccDownloadFailed
661          *              The DCC download failed event
662          */
663         @Subscribe
664         public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
665                 Download download = downloads.get(dccDownloadFailed.dccReceiver().filename());
666                 if (download == null) {
667                         /* probably shouldn’t happen. */
668                         return;
669                 }
670
671                 try {
672                         Closeables.close(download.outputStream(), true);
673                         eventBus.post(new DownloadFailed(download));
674                         dccReceivers.remove(dccDownloadFailed.dccReceiver());
675                         downloads.remove(download);
676                 } catch (IOException ioe1) {
677                         /* swallow silently. */
678                 }
679         }
680
681         //
682         // PRIVATE METHODS
683         //
684
685         /**
686          * Searches all current connections for the given connection, returning the
687          * associated network.
688          *
689          * @param connection
690          *              The connection to get the network for
691          * @return The network belonging to the connection, or {@link
692          *         Optional#absent()}
693          */
694         private Optional<Network> getNetwork(Connection connection) {
695                 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
696                         if (networkConnectionEntry.getValue().equals(connection)) {
697                                 return Optional.of(networkConnectionEntry.getKey());
698                         }
699                 }
700                 return Optional.absent();
701         }
702
703         /**
704          * Returns the configured channel for the given network and name.
705          *
706          * @param network
707          *              The network the channel is located on
708          * @param channelName
709          *              The name of the channel
710          * @return The configured channel, or {@link Optional#absent()} if no
711          *         configured channel matching the given network and name was found
712          */
713         public Optional<Channel> getChannel(Network network, String channelName) {
714                 for (Channel channel : channels) {
715                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
716                                 return Optional.of(channel);
717                         }
718                 }
719                 return Optional.absent();
720         }
721
722         /**
723          * Returns the extra channel for the given network and name.
724          *
725          * @param network
726          *              The network the channel is located on
727          * @param channelName
728          *              The name of the channel
729          * @return The extra channel, or {@link Optional#absent()} if no extra channel
730          *         matching the given network and name was found
731          */
732         public Optional<Channel> getExtraChannel(Network network, String channelName) {
733                 for (Channel channel : extraChannels) {
734                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
735                                 return Optional.of(channel);
736                         }
737                 }
738                 return Optional.absent();
739         }
740
741         /**
742          * Parses {@link Pack} information from the given message.
743          *
744          * @param message
745          *              The message to parse pack information from
746          * @return The parsed pack, or {@link Optional#absent()} if the message could
747          *         not be parsed into a pack
748          */
749         private Optional<Pack> parsePack(String message) {
750                 int squareOpen = message.indexOf('[');
751                 int squareClose = message.indexOf(']', squareOpen);
752                 if ((squareOpen == -1) && (squareClose == -1)) {
753                         return Optional.absent();
754                 }
755                 String packSize = message.substring(squareOpen + 1, squareClose);
756                 String packName = message.substring(message.lastIndexOf(' ') + 1);
757                 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
758                 return Optional.of(new Pack(packIndex, packSize, packName));
759         }
760
761 }