2 * Sone - SoneDownloader.java - Copyright © 2010–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.sone.core;
20 import static freenet.support.io.Closer.close;
21 import static java.lang.String.format;
22 import static java.lang.System.currentTimeMillis;
23 import static java.util.concurrent.TimeUnit.DAYS;
24 import static java.util.logging.Logger.getLogger;
26 import java.io.InputStream;
27 import java.util.HashSet;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
32 import net.pterodactylus.sone.core.FreenetInterface.Fetched;
33 import net.pterodactylus.sone.data.Sone;
34 import net.pterodactylus.sone.data.Sone.SoneStatus;
35 import net.pterodactylus.util.service.AbstractService;
37 import freenet.client.FetchResult;
38 import freenet.client.async.ClientContext;
39 import freenet.client.async.USKCallback;
40 import freenet.keys.FreenetURI;
41 import freenet.keys.USK;
42 import freenet.node.RequestStarter;
43 import freenet.support.api.Bucket;
44 import freenet.support.io.Closer;
45 import com.db4o.ObjectContainer;
47 import com.google.common.annotations.VisibleForTesting;
50 * The Sone downloader is responsible for download Sones as they are updated.
52 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
54 public class SoneDownloaderImpl extends AbstractService implements SoneDownloader {
57 private static final Logger logger = getLogger("Sone.Downloader");
59 /** The maximum protocol version. */
60 private static final int MAX_PROTOCOL_VERSION = 0;
63 private final Core core;
64 private final SoneParser soneParser;
66 /** The Freenet interface. */
67 private final FreenetInterface freenetInterface;
69 /** The sones to update. */
70 private final Set<Sone> sones = new HashSet<Sone>();
73 * Creates a new Sone downloader.
77 * @param freenetInterface
78 * The Freenet interface
80 public SoneDownloaderImpl(Core core, FreenetInterface freenetInterface) {
81 this(core, freenetInterface, new SoneParser(core));
85 * Creates a new Sone downloader.
89 * @param freenetInterface
90 * The Freenet interface
94 SoneDownloaderImpl(Core core, FreenetInterface freenetInterface, SoneParser soneParser) {
95 super("Sone Downloader", false);
97 this.freenetInterface = freenetInterface;
98 this.soneParser = soneParser;
106 * Adds the given Sone to the set of Sones that will be watched for updates.
112 public void addSone(final Sone sone) {
113 if (!sones.add(sone)) {
114 freenetInterface.unregisterUsk(sone);
116 final USKCallback uskCallback = new USKCallback() {
119 @SuppressWarnings("synthetic-access")
120 public void onFoundEdition(long edition, USK key,
121 ObjectContainer objectContainer,
122 ClientContext clientContext, boolean metadata,
123 short codec, byte[] data, boolean newKnownGood,
124 boolean newSlotToo) {
125 logger.log(Level.FINE, format(
126 "Found USK update for Sone “%s” at %s, new known good: %s, new slot too: %s.",
127 sone, key, newKnownGood, newSlotToo));
128 if (edition > sone.getLatestEdition()) {
129 sone.setLatestEdition(edition);
130 new Thread(fetchSoneAction(sone),
131 "Sone Downloader").start();
136 public short getPollingPriorityProgress() {
137 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
141 public short getPollingPriorityNormal() {
142 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
145 if (soneHasBeenActiveRecently(sone)) {
146 freenetInterface.registerActiveUsk(sone.getRequestUri(),
149 freenetInterface.registerPassiveUsk(sone.getRequestUri(),
154 private boolean soneHasBeenActiveRecently(Sone sone) {
155 return (currentTimeMillis() - sone.getTime()) < DAYS.toMillis(7);
158 private void fetchSone(Sone sone) {
159 fetchSone(sone, sone.getRequestUri().sskForUSK());
163 * Fetches the updated Sone. This method can be used to fetch a Sone from a
169 * The URI to fetch the Sone from
172 public void fetchSone(Sone sone, FreenetURI soneUri) {
173 fetchSone(sone, soneUri, false);
177 * Fetches the Sone from the given URI.
182 * The URI of the Sone to fetch
184 * {@code true} to only fetch and parse the Sone, {@code false}
185 * to {@link Core#updateSone(Sone) update} it in the core
186 * @return The downloaded Sone, or {@code null} if the Sone could not be
190 public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
191 logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri));
192 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
193 sone.setStatus(SoneStatus.downloading);
195 Fetched fetchResults = freenetInterface.fetchUri(requestUri);
196 if (fetchResults == null) {
197 /* TODO - mark Sone as bad. */
200 logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
201 Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
202 if (parsedSone != null) {
204 parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
205 core.updateSone(parsedSone);
211 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
216 * Parses a Sone from a fetch result.
218 * @param originalSone
219 * The sone to parse, or {@code null} if the Sone is yet unknown
224 * @return The parsed Sone, or {@code null} if the Sone could not be parsed
226 private Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
227 logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone));
228 Bucket soneBucket = fetchResult.asBucket();
229 InputStream soneInputStream = null;
231 soneInputStream = soneBucket.getInputStream();
232 Sone parsedSone = soneParser.parseSone(originalSone,
234 if (parsedSone != null) {
235 parsedSone.setLatestEdition(requestUri.getEdition());
238 } catch (Exception e1) {
239 logger.log(Level.WARNING, String.format("Could not parse Sone from %s!", requestUri), e1);
241 close(soneInputStream);
248 public Runnable fetchSoneWithUriAction(final Sone sone) {
249 return new Runnable() {
252 fetchSone(sone, sone.getRequestUri());
258 public Runnable fetchSoneAction(final Sone sone) {
259 return new Runnable() {
269 protected void serviceStop() {
270 for (Sone sone : sones) {
271 freenetInterface.unregisterUsk(sone);