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