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;
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;
29 import java.util.Map.Entry;
30 import java.util.concurrent.TimeUnit;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
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;
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;
79 * The core of XDCC Downloader.
81 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
83 public class Core extends AbstractExecutionThreadService {
86 private static final Logger logger = Logger.getLogger(Core.class.getName());
89 private final EventBus eventBus;
91 /** The temporary directory to download files to. */
92 private final String temporaryDirectory;
94 /** The directory to move finished downloads to. */
95 private final String finalDirectory;
97 /** The channels that should be monitored. */
98 private final Collection<Channel> channels = Sets.newHashSet();
100 /** The channels that are currentlymonitored. */
101 private final Collection<Channel> joinedChannels = Sets.newHashSet();
103 /** The channels that are joined but not configured. */
104 private final Collection<Channel> extraChannels = Sets.newHashSet();
106 /** The current network connections. */
107 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
109 /** The currently known bots. */
110 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
112 /** The current downloads. */
113 private final Map<String, Download> downloads = Maps.newHashMap();
115 /** The current DCC receivers. */
116 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
119 * Creates a new core.
123 * @param temporaryDirectory
124 * The directory to download files to
125 * @param finalDirectory
126 * The directory to move finished files to
129 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
130 this.eventBus = eventBus;
131 this.temporaryDirectory = temporaryDirectory;
132 this.finalDirectory = finalDirectory;
140 * Returns all configured channels. Due to various circumstances, configured
141 * channels might not actually be joined.
143 * @return All configured channels
145 public Collection<Channel> channels() {
146 return ImmutableSet.copyOf(channels);
150 * Returns all currently joined channels.
152 * @return All currently joined channels
154 public Collection<Channel> joinedChannels() {
155 return ImmutableSet.copyOf(joinedChannels);
159 * Returns all currently joined channels that are not configured.
161 * @return All currently joined but not configured channels
163 public Collection<Channel> extraChannels() {
164 return ImmutableSet.copyOf(extraChannels);
168 * Returns all currently known bots.
170 * @return All currently known bots
172 public Collection<Bot> bots() {
173 return networkBots.values();
177 * Returns the currently active DCC receivers.
179 * @return The currently active DCC receivers
181 public Collection<DccReceiver> dccReceivers() {
190 * Adds a channel to monitor.
193 * The channel to monitor
195 public void addChannel(Channel channel) {
196 channels.add(channel);
200 * Fetches the given pack from the given bot.
203 * The bot to fetch the pack from
207 public void fetch(Bot bot, Pack pack) {
208 Connection connection = networkConnections.get(bot.network());
209 if (connection == null) {
213 Download download = new Download(bot, pack);
214 downloads.put(pack.name(), download);
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);
224 // ABSTRACTIDLESERVICE METHODS
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());
234 /* notify listeners. */
235 eventBus.post(new CoreStarted(this));
239 protected void run() throws Exception {
240 while (isRunning()) {
242 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
243 } catch (InterruptedException ie1) {
247 /* find channels that should be monitored but are not. */
248 for (Channel channel : channels) {
249 if (joinedChannels.contains(channel)) {
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());
264 protected void shutDown() {
272 * Starts a new connection for the given network if no such connection exists
276 * The network to connect to
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())));
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);
299 * If a connection to a network has been established, the channels associated
300 * with this network are joined.
302 * @param connectionEstablished
303 * The connection established event
306 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
308 /* get network for connection. */
309 Optional<Network> network = getNetwork(connectionEstablished.connection());
312 if (!network.isPresent()) {
316 /* join all channels on this network. */
317 for (Channel channel : channels) {
318 if (channel.network().equals(network.get())) {
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);
329 * Shows a message when a channel was joined by us.
331 * @param channelJoined
332 * The channel joined event
335 public void channelJoined(ChannelJoined channelJoined) {
336 if (channelJoined.connection().isSource(channelJoined.client())) {
337 Optional<Network> network = getNetwork(channelJoined.connection());
338 if (!network.isPresent()) {
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()));
350 joinedChannels.add(channel.get());
351 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
356 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
359 * The channel left event
362 public void channelLeft(ChannelLeft channelLeft) {
363 Optional<Network> network = getNetwork(channelLeft.connection());
364 if (!network.isPresent()) {
368 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
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. */
381 extraChannels.remove(channel);
383 channels.remove(channel.get());
386 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
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())));
399 * Removes a client (which may be a bot) from the table of known bots.
402 * The client quit event
405 public void clientQuit(ClientQuit clientQuit) {
406 Optional<Network> network = getNetwork(clientQuit.connection());
407 if (!network.isPresent()) {
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())));
418 * If the nickname of a bit changes, remove it from the old name and store it
419 * under the new name.
421 * @param nicknameChanged
422 * The nickname changed event
425 public void nicknameChanged(NicknameChanged nicknameChanged) {
426 Optional<Network> network = getNetwork(nicknameChanged.connection());
427 if (!network.isPresent()) {
431 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
436 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
440 * If a message on a channel is received, it is parsed for pack information
441 * with is then added to a bot.
443 * @param channelMessageReceived
444 * The channel message received event
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. */
454 Optional<Network> network = getNetwork(channelMessageReceived.connection());
455 if (!network.isPresent()) {
456 /* message for unknown connection? */
460 /* parse pack information. */
461 Optional<Pack> pack = parsePack(message);
462 if (!pack.isPresent()) {
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));
473 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
478 bot.addPack(pack.get());
479 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
483 * Forward all private messages to every console.
485 * @param privateMessageReceived
486 * The private message recevied event
489 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
490 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
494 * Starts a DCC download.
496 * @param dccSendReceived
500 public void dccSendReceived(DccSendReceived dccSendReceived) {
501 Optional<Network> network = getNetwork(dccSendReceived.connection());
502 if (!network.isPresent()) {
506 Download download = downloads.get(dccSendReceived.filename());
507 if (download == null) {
508 /* unknown download, ignore. */
512 /* check if the file already exists. */
513 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
514 if (outputFile.exists()) {
515 long existingFileSize = outputFile.length();
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())));
523 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
526 /* remove download. */
527 downloads.remove(download);
531 /* file not complete yet, DCC resume it. */
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())));
542 /* file does not exist, start the download. */
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);
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())));
556 public void dccAcceptReceived(DccAcceptReceived dccAcceptReceived) {
557 Optional<Network> network = getNetwork(dccAcceptReceived.connection());
558 if (!network.isPresent()) {
562 Download download = downloads.get(dccAcceptReceived.filename());
563 if (download == null) {
564 /* unknown download, ignore. */
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()));
574 downloads.remove(download);
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);
582 eventBus.post(new DownloadStarted(download));
583 } catch (FileNotFoundException fnfe1) {
588 * Closes the output stream of the download and moves the file to the final
591 * @param dccDownloadFinished
592 * The DCC download finished event
595 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
596 Download download = downloads.get(dccDownloadFinished.dccReceiver().filename());
597 if (download == null) {
598 /* probably shouldn’t happen. */
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);
616 * Closes the output stream and notifies all listeners of the failure.
618 * @param dccDownloadFailed
619 * The DCC download failed event
622 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
623 Download download = downloads.get(dccDownloadFailed.dccReceiver().filename());
624 if (download == null) {
625 /* probably shouldn’t happen. */
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. */
644 * Searches all current connections for the given connection, returning the
645 * associated network.
648 * The connection to get the network for
649 * @return The network belonging to the connection, or {@link
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());
658 return Optional.absent();
662 * Returns the configured channel for the given network and name.
665 * The network the channel is located on
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
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);
677 return Optional.absent();
681 * Returns the extra channel for the given network and name.
684 * The network the channel is located on
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
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);
696 return Optional.absent();
700 * Parses {@link Pack} information from the given 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
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();
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));