2 * Sone - SoneDownloaderImpl.java - Copyright Ā© 2010ā2019 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 javax.inject.Inject;
34 import net.pterodactylus.sone.data.Sone;
35 import net.pterodactylus.sone.data.Sone.SoneStatus;
36 import net.pterodactylus.util.service.AbstractService;
38 import freenet.client.FetchResult;
39 import freenet.client.async.ClientContext;
40 import freenet.client.async.USKCallback;
41 import freenet.keys.FreenetURI;
42 import freenet.keys.USK;
43 import freenet.node.RequestStarter;
44 import freenet.support.api.Bucket;
47 * The Sone downloader is responsible for download Sones as they are updated.
49 public class SoneDownloaderImpl extends AbstractService implements SoneDownloader {
52 private static final Logger logger = getLogger(SoneDownloaderImpl.class.getName());
54 /** The maximum protocol version. */
55 private static final int MAX_PROTOCOL_VERSION = 0;
58 private final UpdatedSoneProcessor updatedSoneProcessor;
59 private final SoneParser soneParser;
61 /** The Freenet interface. */
62 private final FreenetInterface freenetInterface;
64 /** The sones to update. */
65 private final Set<Sone> sones = new HashSet<>();
68 SoneDownloaderImpl(UpdatedSoneProcessor updatedSoneProcessor, FreenetInterface freenetInterface, SoneParser soneParser) {
69 super("Sone Downloader", false);
70 this.updatedSoneProcessor = updatedSoneProcessor;
71 this.freenetInterface = freenetInterface;
72 this.soneParser = soneParser;
80 * Adds the given Sone to the set of Sones that will be watched for updates.
86 public void addSone(final Sone sone) {
87 if (!sones.add(sone)) {
88 freenetInterface.unregisterUsk(sone);
90 final USKCallback uskCallback = new USKCallback() {
93 @SuppressWarnings("synthetic-access")
94 public void onFoundEdition(long edition, USK key,
95 ClientContext clientContext, boolean metadata,
96 short codec, byte[] data, boolean newKnownGood,
98 logger.log(Level.FINE, format(
99 "Found USK update for Sone ā%sā at %s, new known good: %s, new slot too: %s.",
100 sone, key, newKnownGood, newSlotToo));
101 if (edition > sone.getLatestEdition()) {
102 sone.setLatestEdition(edition);
103 new Thread(fetchSoneAsSskAction(sone),
104 "Sone Downloader").start();
109 public short getPollingPriorityProgress() {
110 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
114 public short getPollingPriorityNormal() {
115 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
118 if (soneHasBeenActiveRecently(sone)) {
119 freenetInterface.registerActiveUsk(sone.getRequestUri(),
122 freenetInterface.registerPassiveUsk(sone.getRequestUri(),
127 private boolean soneHasBeenActiveRecently(Sone sone) {
128 return (currentTimeMillis() - sone.getTime()) < DAYS.toMillis(7);
131 private void fetchSoneAsSsk(Sone sone) {
132 fetchSone(sone, sone.getRequestUri().sskForUSK(), false);
136 * Fetches the Sone from the given URI.
141 * The URI of the Sone to fetch
143 * {@code true} to only fetch and parse the Sone, {@code false}
144 * to {@link Core#updateSone(Sone) update} it in the core
145 * @return The downloaded Sone, or {@code null} if the Sone could not be
149 public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
150 logger.log(Level.FINE, String.format("Starting fetch for Sone ā%sā from %sā¦", sone, soneUri));
151 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
152 sone.setStatus(SoneStatus.downloading);
154 Fetched fetchResults = freenetInterface.fetchUri(requestUri);
155 if (fetchResults == null) {
156 /* TODO - mark Sone as bad. */
159 logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
160 Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
161 if (parsedSone != null) {
163 parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
164 updatedSoneProcessor.updateSone(parsedSone);
170 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
175 * Parses a Sone from a fetch result.
177 * @param originalSone
178 * The sone to parse, or {@code null} if the Sone is yet unknown
183 * @return The parsed Sone, or {@code null} if the Sone could not be parsed
185 private Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
186 logger.finest(() -> format("Parsing FetchResult (%d bytes, %s) for %sā¦", fetchResult.size(), fetchResult.getMimeType(), originalSone));
187 Bucket soneBucket = fetchResult.asBucket();
188 InputStream soneInputStream = null;
190 soneInputStream = soneBucket.getInputStream();
191 Sone parsedSone = soneParser.parseSone(originalSone,
193 if (parsedSone != null) {
194 logger.finer(() -> format("Sone %s was successfully parsed.", parsedSone));
195 parsedSone.setLatestEdition(requestUri.getEdition());
198 } catch (Exception e1) {
199 logger.log(Level.WARNING, e1, () -> format("Could not parse Sone from %s!", requestUri));
201 close(soneInputStream);
208 public Runnable fetchSoneAsUskAction(final Sone sone) {
209 return new Runnable() {
212 fetchSone(sone, sone.getRequestUri(), false);
218 public Runnable fetchSoneAsSskAction(final Sone sone) {
219 return new Runnable() {
222 fetchSoneAsSsk(sone);
229 protected void serviceStop() {
230 for (Sone sone : sones) {
231 freenetInterface.unregisterUsk(sone);