f3d5068d7bbb61cd7d598e3071e52af1257982b3
[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 javax.inject.Inject;
33
34 import net.pterodactylus.sone.core.FreenetInterface.Fetched;
35 import net.pterodactylus.sone.data.Sone;
36 import net.pterodactylus.sone.data.Sone.SoneStatus;
37 import net.pterodactylus.util.service.AbstractService;
38
39 import freenet.client.FetchResult;
40 import freenet.client.async.ClientContext;
41 import freenet.client.async.USKCallback;
42 import freenet.keys.FreenetURI;
43 import freenet.keys.USK;
44 import freenet.node.RequestStarter;
45 import freenet.support.api.Bucket;
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          * @param soneParser
78          */
79         @Inject
80         SoneDownloaderImpl(Core core, FreenetInterface freenetInterface, SoneParser soneParser) {
81                 super("Sone Downloader", false);
82                 this.core = core;
83                 this.freenetInterface = freenetInterface;
84                 this.soneParser = soneParser;
85         }
86
87         //
88         // ACTIONS
89         //
90
91         /**
92          * Adds the given Sone to the set of Sones that will be watched for updates.
93          *
94          * @param sone
95          *              The Sone to add
96          */
97         @Override
98         public void addSone(final Sone sone) {
99                 if (!sones.add(sone)) {
100                         freenetInterface.unregisterUsk(sone);
101                 }
102                 final USKCallback uskCallback = new USKCallback() {
103
104                         @Override
105                         @SuppressWarnings("synthetic-access")
106                         public void onFoundEdition(long edition, USK key,
107                                         ClientContext clientContext, boolean metadata,
108                                         short codec, byte[] data, boolean newKnownGood,
109                                         boolean newSlotToo) {
110                                 logger.log(Level.FINE, format(
111                                                 "Found USK update for Sone “%s” at %s, new known good: %s, new slot too: %s.",
112                                                 sone, key, newKnownGood, newSlotToo));
113                                 if (edition > sone.getLatestEdition()) {
114                                         sone.setLatestEdition(edition);
115                                         new Thread(fetchSoneAsSskAction(sone),
116                                                         "Sone Downloader").start();
117                                 }
118                         }
119
120                         @Override
121                         public short getPollingPriorityProgress() {
122                                 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
123                         }
124
125                         @Override
126                         public short getPollingPriorityNormal() {
127                                 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
128                         }
129                 };
130                 if (soneHasBeenActiveRecently(sone)) {
131                         freenetInterface.registerActiveUsk(sone.getRequestUri(),
132                                         uskCallback);
133                 } else {
134                         freenetInterface.registerPassiveUsk(sone.getRequestUri(),
135                                         uskCallback);
136                 }
137         }
138
139         private boolean soneHasBeenActiveRecently(Sone sone) {
140                 return (currentTimeMillis() - sone.getTime()) < DAYS.toMillis(7);
141         }
142
143         private void fetchSoneAsSsk(Sone sone) {
144                 fetchSone(sone, sone.getRequestUri().sskForUSK(), false);
145         }
146
147         /**
148          * Fetches the Sone from the given URI.
149          *
150          * @param sone
151          *              The Sone to fetch
152          * @param soneUri
153          *              The URI of the Sone to fetch
154          * @param fetchOnly
155          *              {@code true} to only fetch and parse the Sone, {@code false}
156          *              to {@link Core#updateSone(Sone) update} it in the core
157          * @return The downloaded Sone, or {@code null} if the Sone could not be
158          *         downloaded
159          */
160         @Override
161         public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
162                 logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri));
163                 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
164                 sone.setStatus(SoneStatus.downloading);
165                 try {
166                         Fetched fetchResults = freenetInterface.fetchUri(requestUri);
167                         if (fetchResults == null) {
168                                 /* TODO - mark Sone as bad. */
169                                 return null;
170                         }
171                         logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
172                         Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
173                         if (parsedSone != null) {
174                                 if (!fetchOnly) {
175                                         parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
176                                         core.updateSone(parsedSone);
177                                         addSone(parsedSone);
178                                 }
179                         }
180                         return parsedSone;
181                 } finally {
182                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
183                 }
184         }
185
186         /**
187          * Parses a Sone from a fetch result.
188          *
189          * @param originalSone
190          *              The sone to parse, or {@code null} if the Sone is yet unknown
191          * @param fetchResult
192          *              The fetch result
193          * @param requestUri
194          *              The requested URI
195          * @return The parsed Sone, or {@code null} if the Sone could not be parsed
196          */
197         private Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
198                 logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone));
199                 Bucket soneBucket = fetchResult.asBucket();
200                 InputStream soneInputStream = null;
201                 try {
202                         soneInputStream = soneBucket.getInputStream();
203                         Sone parsedSone = soneParser.parseSone(originalSone,
204                                         soneInputStream);
205                         if (parsedSone != null) {
206                                 parsedSone.setLatestEdition(requestUri.getEdition());
207                         }
208                         return parsedSone;
209                 } catch (Exception e1) {
210                         logger.log(Level.WARNING, String.format("Could not parse Sone from %s!", requestUri), e1);
211                 } finally {
212                         close(soneInputStream);
213                         close(soneBucket);
214                 }
215                 return null;
216         }
217
218         @Override
219         public Runnable fetchSoneAsUskAction(final Sone sone) {
220                 return new Runnable() {
221                         @Override
222                         public void run() {
223                                 fetchSone(sone, sone.getRequestUri(), false);
224                         }
225                 };
226         }
227
228         @Override
229         public Runnable fetchSoneAsSskAction(final Sone sone) {
230                 return new Runnable() {
231                         @Override
232                         public void run() {
233                                 fetchSoneAsSsk(sone);
234                         }
235                 };
236         }
237
238         /** {@inheritDoc} */
239         @Override
240         protected void serviceStop() {
241                 for (Sone sone : sones) {
242                         freenetInterface.unregisterUsk(sone);
243                 }
244         }
245
246 }