a8591061fb9658b9a3a0f831d0da8a8cd120b095
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneDownloaderImpl.java
1 /*
2  * Sone - SoneDownloaderImpl.java - Copyright © 2010–2016 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.sone.core;
19
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;
25
26 import java.io.InputStream;
27 import java.util.HashSet;
28 import java.util.Set;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
31
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;
36
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
45 import com.google.common.annotations.VisibleForTesting;
46
47 /**
48  * The Sone downloader is responsible for download Sones as they are updated.
49  *
50  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
51  */
52 public class SoneDownloaderImpl extends AbstractService implements SoneDownloader {
53
54         /** The logger. */
55         private static final Logger logger = getLogger(SoneDownloaderImpl.class.getName());
56
57         /** The maximum protocol version. */
58         private static final int MAX_PROTOCOL_VERSION = 0;
59
60         /** The core. */
61         private final Core core;
62         private final SoneParser soneParser;
63
64         /** The Freenet interface. */
65         private final FreenetInterface freenetInterface;
66
67         /** The sones to update. */
68         private final Set<Sone> sones = new HashSet<Sone>();
69
70         /**
71          * Creates a new Sone downloader.
72          *
73          * @param core
74          *              The core
75          * @param freenetInterface
76          *              The Freenet interface
77          */
78         public SoneDownloaderImpl(Core core, FreenetInterface freenetInterface) {
79                 this(core, freenetInterface, new SoneParser(core));
80         }
81
82         /**
83          * Creates a new Sone downloader.
84          *
85          * @param core
86          *              The core
87          * @param freenetInterface
88          *              The Freenet interface
89          * @param soneParser
90          */
91         @VisibleForTesting
92         SoneDownloaderImpl(Core core, FreenetInterface freenetInterface, SoneParser soneParser) {
93                 super("Sone Downloader", false);
94                 this.core = core;
95                 this.freenetInterface = freenetInterface;
96                 this.soneParser = soneParser;
97         }
98
99         //
100         // ACTIONS
101         //
102
103         /**
104          * Adds the given Sone to the set of Sones that will be watched for updates.
105          *
106          * @param sone
107          *              The Sone to add
108          */
109         @Override
110         public void addSone(final Sone sone) {
111                 if (!sones.add(sone)) {
112                         freenetInterface.unregisterUsk(sone);
113                 }
114                 final USKCallback uskCallback = new USKCallback() {
115
116                         @Override
117                         @SuppressWarnings("synthetic-access")
118                         public void onFoundEdition(long edition, USK key,
119                                         ClientContext clientContext, boolean metadata,
120                                         short codec, byte[] data, boolean newKnownGood,
121                                         boolean newSlotToo) {
122                                 logger.log(Level.FINE, format(
123                                                 "Found USK update for Sone “%s” at %s, new known good: %s, new slot too: %s.",
124                                                 sone, key, newKnownGood, newSlotToo));
125                                 if (edition > sone.getLatestEdition()) {
126                                         sone.setLatestEdition(edition);
127                                         new Thread(fetchSoneAction(sone),
128                                                         "Sone Downloader").start();
129                                 }
130                         }
131
132                         @Override
133                         public short getPollingPriorityProgress() {
134                                 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
135                         }
136
137                         @Override
138                         public short getPollingPriorityNormal() {
139                                 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
140                         }
141                 };
142                 if (soneHasBeenActiveRecently(sone)) {
143                         freenetInterface.registerActiveUsk(sone.getRequestUri(),
144                                         uskCallback);
145                 } else {
146                         freenetInterface.registerPassiveUsk(sone.getRequestUri(),
147                                         uskCallback);
148                 }
149         }
150
151         private boolean soneHasBeenActiveRecently(Sone sone) {
152                 return (currentTimeMillis() - sone.getTime()) < DAYS.toMillis(7);
153         }
154
155         private void fetchSone(Sone sone) {
156                 fetchSone(sone, sone.getRequestUri().sskForUSK());
157         }
158
159         /**
160          * Fetches the updated Sone. This method can be used to fetch a Sone from a
161          * specific URI.
162          *
163          * @param sone
164          *              The Sone to fetch
165          * @param soneUri
166          *              The URI to fetch the Sone from
167          */
168         @Override
169         public void fetchSone(Sone sone, FreenetURI soneUri) {
170                 fetchSone(sone, soneUri, false);
171         }
172
173         /**
174          * Fetches the Sone from the given URI.
175          *
176          * @param sone
177          *              The Sone to fetch
178          * @param soneUri
179          *              The URI of the Sone to fetch
180          * @param fetchOnly
181          *              {@code true} to only fetch and parse the Sone, {@code false}
182          *              to {@link Core#updateSone(Sone) update} it in the core
183          * @return The downloaded Sone, or {@code null} if the Sone could not be
184          *         downloaded
185          */
186         @Override
187         public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
188                 logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri));
189                 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
190                 sone.setStatus(SoneStatus.downloading);
191                 try {
192                         Fetched fetchResults = freenetInterface.fetchUri(requestUri);
193                         if (fetchResults == null) {
194                                 /* TODO - mark Sone as bad. */
195                                 return null;
196                         }
197                         logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
198                         Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
199                         if (parsedSone != null) {
200                                 if (!fetchOnly) {
201                                         parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
202                                         core.updateSone(parsedSone);
203                                         addSone(parsedSone);
204                                 }
205                         }
206                         return parsedSone;
207                 } finally {
208                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
209                 }
210         }
211
212         /**
213          * Parses a Sone from a fetch result.
214          *
215          * @param originalSone
216          *              The sone to parse, or {@code null} if the Sone is yet unknown
217          * @param fetchResult
218          *              The fetch result
219          * @param requestUri
220          *              The requested URI
221          * @return The parsed Sone, or {@code null} if the Sone could not be parsed
222          */
223         private Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
224                 logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone));
225                 Bucket soneBucket = fetchResult.asBucket();
226                 InputStream soneInputStream = null;
227                 try {
228                         soneInputStream = soneBucket.getInputStream();
229                         Sone parsedSone = soneParser.parseSone(originalSone,
230                                         soneInputStream);
231                         if (parsedSone != null) {
232                                 parsedSone.setLatestEdition(requestUri.getEdition());
233                         }
234                         return parsedSone;
235                 } catch (Exception e1) {
236                         logger.log(Level.WARNING, String.format("Could not parse Sone from %s!", requestUri), e1);
237                 } finally {
238                         close(soneInputStream);
239                         close(soneBucket);
240                 }
241                 return null;
242         }
243
244         @Override
245         public Runnable fetchSoneWithUriAction(final Sone sone) {
246                 return new Runnable() {
247                         @Override
248                         public void run() {
249                                 fetchSone(sone, sone.getRequestUri());
250                         }
251                 };
252         }
253
254         @Override
255         public Runnable fetchSoneAction(final Sone sone) {
256                 return new Runnable() {
257                         @Override
258                         public void run() {
259                                 fetchSone(sone);
260                         }
261                 };
262         }
263
264         /** {@inheritDoc} */
265         @Override
266         protected void serviceStop() {
267                 for (Sone sone : sones) {
268                         freenetInterface.unregisterUsk(sone);
269                 }
270         }
271
272 }