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