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