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