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.logging.Level;
31 import java.util.logging.Logger;
33 import net.pterodactylus.irc.Connection;
34 import net.pterodactylus.irc.ConnectionBuilder;
35 import net.pterodactylus.irc.DccReceiver;
36 import net.pterodactylus.irc.event.ChannelJoined;
37 import net.pterodactylus.irc.event.ChannelLeft;
38 import net.pterodactylus.irc.event.ChannelMessageReceived;
39 import net.pterodactylus.irc.event.ClientQuit;
40 import net.pterodactylus.irc.event.ConnectionEstablished;
41 import net.pterodactylus.irc.event.DccAcceptReceived;
42 import net.pterodactylus.irc.event.DccDownloadFailed;
43 import net.pterodactylus.irc.event.DccDownloadFinished;
44 import net.pterodactylus.irc.event.DccSendReceived;
45 import net.pterodactylus.irc.event.NicknameChanged;
46 import net.pterodactylus.irc.event.PrivateMessageReceived;
47 import net.pterodactylus.irc.util.MessageCleaner;
48 import net.pterodactylus.irc.util.RandomNickname;
49 import net.pterodactylus.xdcc.core.event.BotAdded;
50 import net.pterodactylus.xdcc.core.event.CoreStarted;
51 import net.pterodactylus.xdcc.core.event.DownloadFailed;
52 import net.pterodactylus.xdcc.core.event.DownloadFinished;
53 import net.pterodactylus.xdcc.core.event.DownloadStarted;
54 import net.pterodactylus.xdcc.core.event.GenericError;
55 import net.pterodactylus.xdcc.core.event.GenericMessage;
56 import net.pterodactylus.xdcc.core.event.MessageReceived;
57 import net.pterodactylus.xdcc.data.Bot;
58 import net.pterodactylus.xdcc.data.Channel;
59 import net.pterodactylus.xdcc.data.Download;
60 import net.pterodactylus.xdcc.data.Network;
61 import net.pterodactylus.xdcc.data.Pack;
62 import net.pterodactylus.xdcc.data.Server;
64 import com.google.common.base.Optional;
65 import com.google.common.collect.HashBasedTable;
66 import com.google.common.collect.ImmutableSet;
67 import com.google.common.collect.Lists;
68 import com.google.common.collect.Maps;
69 import com.google.common.collect.Sets;
70 import com.google.common.collect.Table;
71 import com.google.common.eventbus.EventBus;
72 import com.google.common.eventbus.Subscribe;
73 import com.google.common.io.Closeables;
74 import com.google.common.util.concurrent.AbstractIdleService;
75 import com.google.inject.Inject;
78 * The core of XDCC Downloader.
80 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
82 public class Core extends AbstractIdleService {
85 private static final Logger logger = Logger.getLogger(Core.class.getName());
88 private final EventBus eventBus;
90 /** The temporary directory to download files to. */
91 private final String temporaryDirectory;
93 /** The directory to move finished downloads to. */
94 private final String finalDirectory;
96 /** The channels that should be monitored. */
97 private final Collection<Channel> channels = Sets.newHashSet();
99 /** The channels that are currentlymonitored. */
100 private final Collection<Channel> joinedChannels = Sets.newHashSet();
102 /** The channels that are joined but not configured. */
103 private final Collection<Channel> extraChannels = Sets.newHashSet();
105 /** The current network connections. */
106 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
108 /** The currently known bots. */
109 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
111 /** The current downloads. */
112 private final Map<String, Download> downloads = Maps.newHashMap();
114 /** The current DCC receivers. */
115 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
118 * Creates a new core.
122 * @param temporaryDirectory
123 * The directory to download files to
124 * @param finalDirectory
125 * The directory to move finished files to
128 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
129 this.eventBus = eventBus;
130 this.temporaryDirectory = temporaryDirectory;
131 this.finalDirectory = finalDirectory;
139 * Returns all configured channels. Due to various circumstances, configured
140 * channels might not actually be joined.
142 * @return All configured channels
144 public Collection<Channel> channels() {
145 return ImmutableSet.copyOf(channels);
149 * Returns all currently joined channels.
151 * @return All currently joined channels
153 public Collection<Channel> joinedChannels() {
154 return ImmutableSet.copyOf(joinedChannels);
158 * Returns all currently joined channels that are not configured.
160 * @return All currently joined but not configured channels
162 public Collection<Channel> extraChannels() {
163 return ImmutableSet.copyOf(extraChannels);
167 * Returns all currently known bots.
169 * @return All currently known bots
171 public Collection<Bot> bots() {
172 return networkBots.values();
176 * Returns the currently active DCC receivers.
178 * @return The currently active DCC receivers
180 public Collection<DccReceiver> dccReceivers() {
189 * Adds a channel to monitor.
192 * The channel to monitor
194 public void addChannel(Channel channel) {
195 channels.add(channel);
199 * Fetches the given pack from the given bot.
202 * The bot to fetch the pack from
206 public void fetch(Bot bot, Pack pack) {
207 Connection connection = networkConnections.get(bot.network());
208 if (connection == null) {
212 Download download = new Download(bot, pack);
213 downloads.put(pack.name(), download);
216 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
217 } catch (IOException ioe1) {
218 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
223 // ABSTRACTIDLESERVICE METHODS
227 protected void startUp() {
228 for (Channel channel : channels) {
229 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
230 if (!networkConnections.containsKey(channel.network())) {
231 /* select a random server. */
232 List<Server> servers = Lists.newArrayList(channel.network().servers());
233 Server server = servers.get((int) (Math.random() * servers.size()));
234 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
235 connection.username(RandomNickname.get()).realName(RandomNickname.get());
236 networkConnections.put(channel.network(), connection);
241 /* notify listeners. */
242 eventBus.post(new CoreStarted(this));
246 protected void shutDown() {
254 * If a connection to a network has been established, the channels associated
255 * with this network are joined.
257 * @param connectionEstablished
258 * The connection established event
261 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
263 /* get network for connection. */
264 Optional<Network> network = getNetwork(connectionEstablished.connection());
267 if (!network.isPresent()) {
271 /* join all channels on this network. */
272 for (Channel channel : channels) {
273 if (channel.network().equals(network.get())) {
275 connectionEstablished.connection().joinChannel(channel.name());
276 } catch (IOException ioe1) {
277 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
284 * Shows a message when a channel was joined by us.
286 * @param channelJoined
287 * The channel joined event
290 public void channelJoined(ChannelJoined channelJoined) {
291 if (channelJoined.connection().isSource(channelJoined.client())) {
292 Optional<Network> network = getNetwork(channelJoined.connection());
293 if (!network.isPresent()) {
297 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
298 if (!channel.isPresent()) {
299 /* it’s an extra channel. */
300 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
301 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
305 joinedChannels.add(channel.get());
306 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
311 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
314 * The channel left event
317 public void channelLeft(ChannelLeft channelLeft) {
318 Optional<Network> network = getNetwork(channelLeft.connection());
319 if (!network.isPresent()) {
323 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
325 /* maybe it was us? */
326 if (channelLeft.connection().isSource(channelLeft.client())) {
327 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
328 if (!channel.isPresent()) {
329 /* maybe it was an extra channel? */
330 channel = getExtraChannel(network.get(), channelLeft.channel());
331 if (!channel.isPresent()) {
332 /* okay, whatever. */
336 extraChannels.remove(channel);
338 channels.remove(channel.get());
341 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
347 Bot removedBot = networkBots.remove(network.get(), channelLeft.client().nick().get());
348 if (removedBot != null) {
349 eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
354 * Removes a client (which may be a bot) from the table of known bots.
357 * The client quit event
360 public void clientQuit(ClientQuit clientQuit) {
361 Optional<Network> network = getNetwork(clientQuit.connection());
362 if (!network.isPresent()) {
366 Bot removedBot = networkBots.remove(network.get(), clientQuit.client().nick().get());
367 if (removedBot != null) {
368 eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
373 * If the nickname of a bit changes, remove it from the old name and store it
374 * under the new name.
376 * @param nicknameChanged
377 * The nickname changed event
380 public void nicknameChanged(NicknameChanged nicknameChanged) {
381 Optional<Network> network = getNetwork(nicknameChanged.connection());
382 if (!network.isPresent()) {
386 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
391 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
395 * If a message on a channel is received, it is parsed for pack information
396 * with is then added to a bot.
398 * @param channelMessageReceived
399 * The channel message received event
402 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
403 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
404 if (!message.startsWith("#")) {
405 /* most probably not a pack announcement. */
409 Optional<Network> network = getNetwork(channelMessageReceived.connection());
410 if (!network.isPresent()) {
411 /* message for unknown connection? */
415 /* parse pack information. */
416 Optional<Pack> pack = parsePack(message);
417 if (!pack.isPresent()) {
422 synchronized (networkBots) {
423 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
424 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
425 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
426 eventBus.post(new BotAdded(bot));
428 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
433 bot.addPack(pack.get());
434 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
438 * Forward all private messages to every console.
440 * @param privateMessageReceived
441 * The private message recevied event
444 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
445 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
449 * Starts a DCC download.
451 * @param dccSendReceived
455 public void dccSendReceived(DccSendReceived dccSendReceived) {
456 Optional<Network> network = getNetwork(dccSendReceived.connection());
457 if (!network.isPresent()) {
461 Download download = downloads.get(dccSendReceived.filename());
462 if (download == null) {
463 /* unknown download, ignore. */
467 /* check if the file already exists. */
468 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
469 if (outputFile.exists()) {
470 long existingFileSize = outputFile.length();
472 /* file already complete? */
473 if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
474 /* file is apparently already complete. just move it. */
475 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
476 eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
478 eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
481 /* remove download. */
482 downloads.remove(download);
486 /* file not complete yet, DCC resume it. */
488 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
489 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
490 } catch (IOException ioe1) {
491 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
497 /* file does not exist, start the download. */
499 OutputStream fileOutputStream = new FileOutputStream(outputFile);
500 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
501 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
502 dccReceivers.add(dccReceiver);
504 eventBus.post(new DownloadStarted(download));
505 } catch (FileNotFoundException fnfe1) {
506 eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
511 public void dccAcceptReceived(DccAcceptReceived dccAcceptReceived) {
512 Optional<Network> network = getNetwork(dccAcceptReceived.connection());
513 if (!network.isPresent()) {
517 Download download = downloads.get(dccAcceptReceived.filename());
518 if (download == null) {
519 /* unknown download, ignore. */
524 File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
525 if (outputFile.length() != dccAcceptReceived.position()) {
526 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
527 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()));
529 downloads.remove(download);
532 OutputStream outputStream = new FileOutputStream(outputFile, true);
533 DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
534 download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
535 dccReceivers.add(dccReceiver);
537 eventBus.post(new DownloadStarted(download));
538 } catch (FileNotFoundException fnfe1) {
543 * Closes the output stream of the download and moves the file to the final
546 * @param dccDownloadFinished
547 * The DCC download finished event
550 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
551 Download download = downloads.get(dccDownloadFinished.dccReceiver().filename());
552 if (download == null) {
553 /* probably shouldn’t happen. */
558 download.outputStream().close();
559 File file = new File(download.filename());
560 file.renameTo(new File(finalDirectory, download.pack().name()));
561 eventBus.post(new DownloadFinished(download));
562 dccReceivers.remove(dccDownloadFinished.dccReceiver());
563 downloads.remove(download);
564 } catch (IOException ioe1) {
565 /* TODO - handle all the errors. */
566 logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
571 * Closes the output stream and notifies all listeners of the failure.
573 * @param dccDownloadFailed
574 * The DCC download failed event
577 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
578 Download download = downloads.get(dccDownloadFailed.dccReceiver().filename());
579 if (download == null) {
580 /* probably shouldn’t happen. */
585 Closeables.close(download.outputStream(), true);
586 eventBus.post(new DownloadFailed(download));
587 dccReceivers.remove(dccDownloadFailed.dccReceiver());
588 downloads.remove(download);
589 } catch (IOException ioe1) {
590 /* swallow silently. */
599 * Searches all current connections for the given connection, returning the
600 * associated network.
603 * The connection to get the network for
604 * @return The network belonging to the connection, or {@link
607 private Optional<Network> getNetwork(Connection connection) {
608 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
609 if (networkConnectionEntry.getValue().equals(connection)) {
610 return Optional.of(networkConnectionEntry.getKey());
613 return Optional.absent();
617 * Returns the configured channel for the given network and name.
620 * The network the channel is located on
622 * The name of the channel
623 * @return The configured channel, or {@link Optional#absent()} if no
624 * configured channel matching the given network and name was found
626 public Optional<Channel> getChannel(Network network, String channelName) {
627 for (Channel channel : channels) {
628 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
629 return Optional.of(channel);
632 return Optional.absent();
636 * Returns the extra channel for the given network and name.
639 * The network the channel is located on
641 * The name of the channel
642 * @return The extra channel, or {@link Optional#absent()} if no extra channel
643 * matching the given network and name was found
645 public Optional<Channel> getExtraChannel(Network network, String channelName) {
646 for (Channel channel : extraChannels) {
647 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
648 return Optional.of(channel);
651 return Optional.absent();
655 * Parses {@link Pack} information from the given message.
658 * The message to parse pack information from
659 * @return The parsed pack, or {@link Optional#absent()} if the message could
660 * not be parsed into a pack
662 private Optional<Pack> parsePack(String message) {
663 int squareOpen = message.indexOf('[');
664 int squareClose = message.indexOf(']', squareOpen);
665 if ((squareOpen == -1) && (squareClose == -1)) {
666 return Optional.absent();
668 String packSize = message.substring(squareOpen + 1, squareClose);
669 String packName = message.substring(message.lastIndexOf(' ') + 1);
670 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
671 return Optional.of(new Pack(packIndex, packSize, packName));