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