2 * Sone - SoneDownloader.java - Copyright © 2010 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.core;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.net.MalformedURLException;
23 import java.util.HashSet;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
28 import net.pterodactylus.sone.core.Core.SoneStatus;
29 import net.pterodactylus.sone.data.Post;
30 import net.pterodactylus.sone.data.Profile;
31 import net.pterodactylus.sone.data.Reply;
32 import net.pterodactylus.sone.data.Sone;
33 import net.pterodactylus.util.collection.Pair;
34 import net.pterodactylus.util.io.Closer;
35 import net.pterodactylus.util.logging.Logging;
36 import net.pterodactylus.util.number.Numbers;
37 import net.pterodactylus.util.service.AbstractService;
38 import net.pterodactylus.util.xml.SimpleXML;
39 import net.pterodactylus.util.xml.XML;
41 import org.w3c.dom.Document;
43 import freenet.client.FetchResult;
44 import freenet.keys.FreenetURI;
45 import freenet.support.api.Bucket;
48 * The Sone downloader is responsible for download Sones as they are updated.
50 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52 public class SoneDownloader extends AbstractService {
55 private static final Logger logger = Logging.getLogger(SoneDownloader.class);
58 private final Core core;
60 /** The Freenet interface. */
61 private final FreenetInterface freenetInterface;
63 /** The sones to update. */
64 private final Set<Sone> sones = new HashSet<Sone>();
67 * Creates a new Sone downloader.
71 * @param freenetInterface
72 * The Freenet interface
74 public SoneDownloader(Core core, FreenetInterface freenetInterface) {
75 super("Sone Downloader", false);
77 this.freenetInterface = freenetInterface;
85 * Adds the given Sone to the set of Sones that will be watched for updates.
90 public void addSone(Sone sone) {
91 if (sones.add(sone)) {
92 freenetInterface.registerUsk(sone, this);
97 * Removes the given Sone from the downloader.
100 * The Sone to stop watching
102 public void removeSone(Sone sone) {
103 if (sones.remove(sone)) {
104 freenetInterface.unregisterUsk(sone);
109 * Fetches the updated Sone. This method is a callback method for
110 * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
115 public void fetchSone(Sone sone) {
116 if (core.getSoneStatus(sone) == SoneStatus.downloading) {
119 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
120 FreenetURI requestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
121 core.setSoneStatus(sone, SoneStatus.downloading);
123 Pair<FreenetURI, FetchResult> fetchResults = freenetInterface.fetchUri(requestUri);
124 if (fetchResults == null) {
125 /* TODO - mark Sone as bad. */
128 logger.log(Level.FINEST, "Got %d bytes back.", fetchResults.getRight().size());
129 Sone parsedSone = parseSone(sone, fetchResults.getRight(), fetchResults.getLeft());
130 if (parsedSone != null) {
131 core.updateSone(parsedSone);
134 core.setSoneStatus(sone, (sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
139 * Parses a Sone from a fetch result.
141 * @param originalSone
142 * The sone to parse, or {@code null} if the Sone is yet unknown
147 * @return The parsed Sone, or {@code null} if the Sone could not be parsed
149 public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
150 logger.log(Level.FINEST, "Parsing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), originalSone });
151 Bucket soneBucket = fetchResult.asBucket();
152 InputStream soneInputStream = null;
154 soneInputStream = soneBucket.getInputStream();
155 Sone parsedSone = parseSone(originalSone, soneInputStream);
156 if (parsedSone != null) {
157 parsedSone.setRequestUri(requestUri.setMetaString(new String[0]));
160 } catch (IOException ioe1) {
161 logger.log(Level.WARNING, "Could not parse Sone from " + requestUri + "!", ioe1);
163 Closer.close(soneInputStream);
170 * Parses a Sone from the given input stream and creates a new Sone from the
173 * @param originalSone
175 * @param soneInputStream
176 * The input stream to parse the Sone from
177 * @return The parsed Sone
179 public Sone parseSone(Sone originalSone, InputStream soneInputStream) {
180 /* TODO - impose a size limit? */
183 /* XML parsing is not thread-safe. */
184 synchronized (this) {
185 document = XML.transformToDocument(soneInputStream);
187 if (document == null) {
188 /* TODO - mark Sone as bad. */
189 logger.log(Level.WARNING, "Could not parse XML for Sone %s!", new Object[] { originalSone });
193 Sone sone = new Sone(originalSone.getId()).setIdentity(originalSone.getIdentity());
197 soneXml = SimpleXML.fromDocument(document);
198 } catch (NullPointerException npe1) {
199 /* for some reason, invalid XML can cause NPEs. */
200 logger.log(Level.WARNING, "XML for Sone " + sone + " can not be parsed!", npe1);
204 String soneTime = soneXml.getValue("time", null);
205 if (soneTime == null) {
206 /* TODO - mark Sone as bad. */
207 logger.log(Level.WARNING, "Downloaded time for Sone %s was null!", new Object[] { sone });
211 sone.setTime(Long.parseLong(soneTime));
212 } catch (NumberFormatException nfe1) {
213 /* TODO - mark Sone as bad. */
214 logger.log(Level.WARNING, "Downloaded Sone %s with invalid time: %s", new Object[] { sone, soneTime });
218 String soneRequestUri = soneXml.getValue("request-uri", null);
219 if (soneRequestUri != null) {
221 sone.setRequestUri(new FreenetURI(soneRequestUri));
222 } catch (MalformedURLException mue1) {
223 /* TODO - mark Sone as bad. */
224 logger.log(Level.WARNING, "Downloaded Sone " + sone + " has invalid request URI: " + soneRequestUri, mue1);
229 String soneInsertUri = soneXml.getValue("insert-uri", null);
230 if ((soneInsertUri != null) && (sone.getInsertUri() == null)) {
232 sone.setInsertUri(new FreenetURI(soneInsertUri));
233 sone.setLatestEdition(Math.max(sone.getRequestUri().getSuggestedEdition(), sone.getInsertUri().getSuggestedEdition()));
234 } catch (MalformedURLException mue1) {
235 /* TODO - mark Sone as bad. */
236 logger.log(Level.WARNING, "Downloaded Sone " + sone + " has invalid insert URI: " + soneInsertUri, mue1);
241 SimpleXML profileXml = soneXml.getNode("profile");
242 if (profileXml == null) {
243 /* TODO - mark Sone as bad. */
244 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
249 String profileFirstName = profileXml.getValue("first-name", null);
250 String profileMiddleName = profileXml.getValue("middle-name", null);
251 String profileLastName = profileXml.getValue("last-name", null);
252 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
253 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
254 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
255 Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
256 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
259 SimpleXML postsXml = soneXml.getNode("posts");
260 Set<Post> posts = new HashSet<Post>();
261 if (postsXml == null) {
262 /* TODO - mark Sone as bad. */
263 logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
265 for (SimpleXML postXml : postsXml.getNodes("post")) {
266 String postId = postXml.getValue("id", null);
267 String postTime = postXml.getValue("time", null);
268 String postText = postXml.getValue("text", null);
269 if ((postId == null) || (postTime == null) || (postText == null)) {
270 /* TODO - mark Sone as bad. */
271 logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
275 posts.add(core.getPost(postId).setSone(sone).setTime(Long.parseLong(postTime)).setText(postText));
276 } catch (NumberFormatException nfe1) {
277 /* TODO - mark Sone as bad. */
278 logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
285 SimpleXML repliesXml = soneXml.getNode("replies");
286 Set<Reply> replies = new HashSet<Reply>();
287 if (repliesXml == null) {
288 /* TODO - mark Sone as bad. */
289 logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
291 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
292 String replyId = replyXml.getValue("id", null);
293 String replyPostId = replyXml.getValue("post-id", null);
294 String replyTime = replyXml.getValue("time", null);
295 String replyText = replyXml.getValue("text", null);
296 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
297 /* TODO - mark Sone as bad. */
298 logger.log(Level.WARNING, "Downloaded reply for Sone %s with missing data! ID: %s, Post: %s, Time: %s, Text: %s", new Object[] { sone, replyId, replyPostId, replyTime, replyText });
302 replies.add(core.getReply(replyId).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
303 } catch (NumberFormatException nfe1) {
304 /* TODO - mark Sone as bad. */
305 logger.log(Level.WARNING, "Downloaded reply for Sone %s with invalid time: %s", new Object[] { sone, replyTime });
311 /* parse liked post IDs. */
312 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
313 Set<String> likedPostIds = new HashSet<String>();
314 if (likePostIdsXml == null) {
315 /* TODO - mark Sone as bad. */
316 logger.log(Level.WARNING, "Downloaded Sone %s has no post likes!", new Object[] { sone });
318 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
319 String postId = likedPostIdXml.getValue();
320 likedPostIds.add(postId);
324 /* parse liked reply IDs. */
325 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
326 Set<String> likedReplyIds = new HashSet<String>();
327 if (likeReplyIdsXml == null) {
328 /* TODO - mark Sone as bad. */
329 logger.log(Level.WARNING, "Downloaded Sone %s has no reply likes!", new Object[] { sone });
331 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
332 String replyId = likedReplyIdXml.getValue();
333 likedReplyIds.add(replyId);
337 /* okay, apparently everything was parsed correctly. Now import. */
338 /* atomic setter operation on the Sone. */
339 synchronized (sone) {
340 sone.setProfile(profile);
341 sone.setPosts(posts);
342 sone.setReplies(replies);
343 sone.setLikePostIds(likedPostIds);
357 protected void serviceStop() {
358 for (Sone sone : sones) {
359 freenetInterface.unregisterUsk(sone);