eb263ed778005787a8d688b37c12eab93d933848
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneDownloader.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 net.pterodactylus.sone.data.Sone.TO_FREENET_URI;
21
22 import java.io.InputStream;
23 import java.util.HashSet;
24 import java.util.Set;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27
28 import net.pterodactylus.sone.core.FreenetInterface.Fetched;
29 import net.pterodactylus.sone.data.Sone;
30 import net.pterodactylus.sone.data.Sone.SoneStatus;
31 import net.pterodactylus.util.io.Closer;
32 import net.pterodactylus.util.logging.Logging;
33 import net.pterodactylus.util.service.AbstractService;
34
35 import freenet.client.FetchResult;
36 import freenet.keys.FreenetURI;
37 import freenet.support.api.Bucket;
38
39 /**
40  * The Sone downloader is responsible for download Sones as they are updated.
41  *
42  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
43  */
44 public class SoneDownloader extends AbstractService {
45
46         /** The logger. */
47         private static final Logger logger = Logging.getLogger(SoneDownloader.class);
48
49         /** The maximum protocol version. */
50         private static final int MAX_PROTOCOL_VERSION = 0;
51
52         /** The core. */
53         private final Core core;
54
55         /** The Freenet interface. */
56         private final FreenetInterface freenetInterface;
57
58         /** The sones to update. */
59         private final Set<Sone> sones = new HashSet<Sone>();
60
61         /**
62          * Creates a new Sone downloader.
63          *
64          * @param core
65          *            The core
66          * @param freenetInterface
67          *            The Freenet interface
68          */
69         public SoneDownloader(Core core, FreenetInterface freenetInterface) {
70                 super("Sone Downloader", false);
71                 this.core = core;
72                 this.freenetInterface = freenetInterface;
73         }
74
75         //
76         // ACTIONS
77         //
78
79         /**
80          * Adds the given Sone to the set of Sones that will be watched for updates.
81          *
82          * @param sone
83          *            The Sone to add
84          */
85         public void addSone(Sone sone) {
86                 if (!sones.add(sone)) {
87                         freenetInterface.unregisterUsk(sone);
88                 }
89                 freenetInterface.registerUsk(sone, this);
90         }
91
92         /**
93          * Removes the given Sone from the downloader.
94          *
95          * @param sone
96          *            The Sone to stop watching
97          */
98         public void removeSone(Sone sone) {
99                 if (sones.remove(sone)) {
100                         freenetInterface.unregisterUsk(sone);
101                 }
102         }
103
104         /**
105          * Fetches the updated Sone. This method is a callback method for
106          * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
107          *
108          * @param sone
109          *            The Sone to fetch
110          */
111         public void fetchSone(Sone sone) {
112                 fetchSone(sone, TO_FREENET_URI.apply(sone).sskForUSK());
113         }
114
115         /**
116          * Fetches the updated Sone. This method can be used to fetch a Sone from a
117          * specific URI.
118          *
119          * @param sone
120          *            The Sone to fetch
121          * @param soneUri
122          *            The URI to fetch the Sone from
123          */
124         public void fetchSone(Sone sone, FreenetURI soneUri) {
125                 fetchSone(sone, soneUri, false);
126         }
127
128         /**
129          * Fetches the Sone from the given URI.
130          *
131          * @param sone
132          *            The Sone to fetch
133          * @param soneUri
134          *            The URI of the Sone to fetch
135          * @param fetchOnly
136          *            {@code true} to only fetch and parse the Sone, {@code false}
137          *            to {@link Core#updateSone(Sone) update} it in the core
138          * @return The downloaded Sone, or {@code null} if the Sone could not be
139          *         downloaded
140          */
141         public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
142                 logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri));
143                 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
144                 sone.setStatus(SoneStatus.downloading);
145                 try {
146                         Fetched fetchResults = freenetInterface.fetchUri(requestUri);
147                         if (fetchResults == null) {
148                                 /* TODO - mark Sone as bad. */
149                                 return null;
150                         }
151                         logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
152                         Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
153                         if (parsedSone != null) {
154                                 if (!fetchOnly) {
155                                         parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
156                                         core.updateSone(parsedSone);
157                                         addSone(parsedSone);
158                                 }
159                         }
160                         return parsedSone;
161                 } finally {
162                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
163                 }
164         }
165
166         /**
167          * Parses a Sone from a fetch result.
168          *
169          * @param originalSone
170          *            The sone to parse, or {@code null} if the Sone is yet unknown
171          * @param fetchResult
172          *            The fetch result
173          * @param requestUri
174          *            The requested URI
175          * @return The parsed Sone, or {@code null} if the Sone could not be parsed
176          */
177         public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
178                 logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone));
179                 Bucket soneBucket = fetchResult.asBucket();
180                 InputStream soneInputStream = null;
181                 try {
182                         soneInputStream = soneBucket.getInputStream();
183                         Sone parsedSone = parseSone(originalSone, soneInputStream);
184                         if (parsedSone != null) {
185                                 parsedSone.modify().setLatestEdition(requestUri.getEdition()).update();
186                         }
187                         return parsedSone;
188                 } catch (Exception e1) {
189                         logger.log(Level.WARNING, String.format("Could not parse Sone from %s!", requestUri), e1);
190                 } finally {
191                         Closer.close(soneInputStream);
192                         soneBucket.free();
193                 }
194                 return null;
195         }
196
197         /**
198          * Parses a Sone from the given input stream and creates a new Sone from the
199          * parsed data.
200          *
201          * @param originalSone
202          *            The Sone to update
203          * @param soneInputStream
204          *            The input stream to parse the Sone from
205          * @return The parsed Sone
206          */
207         public Sone parseSone(Sone originalSone, InputStream soneInputStream) {
208                 return new SoneParser().parseSone(core.getDatabase(), originalSone, soneInputStream);
209         }
210
211         //
212         // SERVICE METHODS
213         //
214
215         @Override
216         protected void serviceStop() {
217                 for (Sone sone : sones) {
218                         freenetInterface.unregisterUsk(sone);
219                 }
220         }
221
222 }