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