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.io.Closer;
34 import net.pterodactylus.util.logging.Logging;
35 import net.pterodactylus.util.number.Numbers;
36 import net.pterodactylus.util.service.AbstractService;
37 import net.pterodactylus.util.xml.SimpleXML;
38 import net.pterodactylus.util.xml.XML;
40 import org.w3c.dom.Document;
42 import freenet.client.FetchResult;
43 import freenet.keys.FreenetURI;
44 import freenet.support.api.Bucket;
47 * The Sone downloader is responsible for download Sones as they are updated.
49 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
51 public class SoneDownloader extends AbstractService {
54 private static final Logger logger = Logging.getLogger(SoneDownloader.class);
57 private final Core core;
59 /** The Freenet interface. */
60 private final FreenetInterface freenetInterface;
62 /** The sones to update. */
63 private final Set<Sone> sones = new HashSet<Sone>();
66 * Creates a new Sone downloader.
70 * @param freenetInterface
71 * The Freenet interface
73 public SoneDownloader(Core core, FreenetInterface freenetInterface) {
74 super("Sone Downloader", false);
76 this.freenetInterface = freenetInterface;
84 * Adds the given Sone to the set of Sones that will be watched for updates.
89 public void addSone(Sone sone) {
90 if (sones.add(sone)) {
91 freenetInterface.registerUsk(sone, this);
96 * Removes the given Sone from the downloader.
99 * The Sone to stop watching
101 public void removeSone(Sone sone) {
102 if (sones.remove(sone)) {
103 freenetInterface.unregisterUsk(sone);
108 * Fetches the updated Sone. This method is a callback method for
109 * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
114 public void fetchSone(Sone sone) {
115 if (core.getSoneStatus(sone) == SoneStatus.downloading) {
118 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
119 FreenetURI requestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
120 core.setSoneStatus(sone, SoneStatus.downloading);
122 FetchResult fetchResult = freenetInterface.fetchUri(requestUri);
123 if (fetchResult == null) {
124 /* TODO - mark Sone as bad. */
127 logger.log(Level.FINEST, "Got %d bytes back.", fetchResult.size());
128 Sone parsedSone = parseSone(sone, fetchResult, requestUri);
129 if (parsedSone != null) {
130 core.addSone(parsedSone);
133 core.setSoneStatus(sone, (sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
138 * Parses a Sone from a fetch result.
140 * @param originalSone
141 * The sone to parse, or {@code null} if the Sone is yet unknown
146 * @return The parsed Sone, or {@code null} if the Sone could not be parsed
148 public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
149 logger.log(Level.FINEST, "Persing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), originalSone });
150 /* TODO - impose a size limit? */
151 InputStream xmlInputStream = null;
152 Bucket xmlBucket = null;
155 xmlBucket = fetchResult.asBucket();
156 xmlInputStream = xmlBucket.getInputStream();
158 /* XML parsing is not thread-safe. */
159 synchronized (this) {
160 document = XML.transformToDocument(xmlInputStream);
162 if (document == null) {
163 /* TODO - mark Sone as bad. */
164 logger.log(Level.WARNING, "Could not parse XML for Sone %s at %s!", new Object[] { originalSone, requestUri });
169 soneXml = SimpleXML.fromDocument(document);
170 } catch (NullPointerException npe1) {
171 /* for some reason, invalid XML can cause NPEs. */
172 logger.log(Level.WARNING, "XML for Sone " + originalSone + " can not be parsed!", npe1);
177 String soneId = soneXml.getValue("id", null);
178 if ((originalSone != null) && !originalSone.getId().equals(soneId)) {
179 /* TODO - mark Sone as bad. */
180 logger.log(Level.WARNING, "Downloaded ID for Sone %s (%s) does not match known ID (%s)!", new Object[] { originalSone, originalSone.getId(), soneId });
184 /* load Sone from core. */
187 sone = core.getSone(soneId).setRequestUri(requestUri.setMetaString(new String[] {}));
190 String soneName = soneXml.getValue("name", null);
191 if (soneName == null) {
192 /* TODO - mark Sone as bad. */
193 logger.log(Level.WARNING, "Downloaded name for Sone %s was null!", new Object[] { sone });
196 sone.setName(soneName);
198 String soneTime = soneXml.getValue("time", null);
199 if (soneTime == null) {
200 /* TODO - mark Sone as bad. */
201 logger.log(Level.WARNING, "Downloaded time for Sone %s was null!", new Object[] { sone });
205 sone.setTime(Long.parseLong(soneTime));
206 } catch (NumberFormatException nfe1) {
207 /* TODO - mark Sone as bad. */
208 logger.log(Level.WARNING, "Downloaded Sone %s with invalid time: %s", new Object[] { sone, soneTime });
212 SimpleXML profileXml = soneXml.getNode("profile");
213 if (profileXml == null) {
214 /* TODO - mark Sone as bad. */
215 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
220 String profileFirstName = profileXml.getValue("first-name", null);
221 String profileMiddleName = profileXml.getValue("middle-name", null);
222 String profileLastName = profileXml.getValue("last-name", null);
223 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
224 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
225 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
226 Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
227 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
230 SimpleXML postsXml = soneXml.getNode("posts");
231 Set<Post> posts = new HashSet<Post>();
232 if (postsXml == null) {
233 /* TODO - mark Sone as bad. */
234 logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
236 for (SimpleXML postXml : postsXml.getNodes("post")) {
237 String postId = postXml.getValue("id", null);
238 String postTime = postXml.getValue("time", null);
239 String postText = postXml.getValue("text", null);
240 if ((postId == null) || (postTime == null) || (postText == null)) {
241 /* TODO - mark Sone as bad. */
242 logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
246 posts.add(core.getPost(postId).setSone(sone).setTime(Long.parseLong(postTime)).setText(postText));
247 } catch (NumberFormatException nfe1) {
248 /* TODO - mark Sone as bad. */
249 logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
256 SimpleXML repliesXml = soneXml.getNode("replies");
257 Set<Reply> replies = new HashSet<Reply>();
258 if (repliesXml == null) {
259 /* TODO - mark Sone as bad. */
260 logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
262 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
263 String replyId = replyXml.getValue("id", null);
264 String replyPostId = replyXml.getValue("post-id", null);
265 String replyTime = replyXml.getValue("time", null);
266 String replyText = replyXml.getValue("text", null);
267 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
268 /* TODO - mark Sone as bad. */
269 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 });
273 replies.add(core.getReply(replyId).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
274 } catch (NumberFormatException nfe1) {
275 /* TODO - mark Sone as bad. */
276 logger.log(Level.WARNING, "Downloaded reply for Sone %s with invalid time: %s", new Object[] { sone, replyTime });
282 /* parse liked post IDs. */
283 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
284 Set<String> likedPostIds = new HashSet<String>();
285 if (likePostIdsXml == null) {
286 /* TODO - mark Sone as bad. */
287 logger.log(Level.WARNING, "Downloaded Sone %s has no post likes!", new Object[] { sone });
289 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
290 String postId = likedPostIdXml.getValue();
291 likedPostIds.add(postId);
295 /* parse liked reply IDs. */
296 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
297 Set<String> likedReplyIds = new HashSet<String>();
298 if (likeReplyIdsXml == null) {
299 /* TODO - mark Sone as bad. */
300 logger.log(Level.WARNING, "Downloaded Sone %s has no reply likes!", new Object[] { sone });
302 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
303 String replyId = likedReplyIdXml.getValue();
304 likedReplyIds.add(replyId);
308 /* parse known Sones. */
309 SimpleXML knownSonesXml = soneXml.getNode("known-sones");
310 Set<Sone> knownSones = new HashSet<Sone>();
311 if (knownSonesXml == null) {
312 /* TODO - mark Sone as bad. */
313 logger.log(Level.WARNING, "Downloaded Sone %s has no known Sones!", new Object[] { sone });
315 for (SimpleXML knownSoneXml : knownSonesXml.getNodes("known-sone")) {
316 String knownSoneId = knownSoneXml.getValue("sone-id", null);
317 String knownSoneKey = knownSoneXml.getValue("sone-key", null);
318 String knownSoneName = knownSoneXml.getValue("sone-name", null);
319 if ((knownSoneId == null) || (knownSoneKey == null) || (knownSoneName == null)) {
320 /* TODO - mark Sone as bad. */
321 logger.log(Level.WARNING, "Downloaded known Sone for Sone %s with missing data! ID: %s, Key: %s, Name: %s", new Object[] { sone, knownSoneId, knownSoneKey, knownSoneName });
325 knownSones.add(core.getSone(knownSoneId).setRequestUri(new FreenetURI(knownSoneKey)).setName(knownSoneName));
326 } catch (MalformedURLException mue1) {
327 /* TODO - mark Sone as bad. */
328 logger.log(Level.WARNING, "Downloaded known Sone for Sone %s with invalid key: %s", new Object[] { sone, knownSoneKey });
334 /* okay, apparently everything was parsed correctly. Now import. */
335 /* atomic setter operation on the Sone. */
336 synchronized (sone) {
337 sone.setProfile(profile);
338 sone.setPosts(posts);
339 sone.setReplies(replies);
340 sone.setLikePostIds(likedPostIds);
341 sone.setModificationCounter(0);
344 /* add all known Sones to core for downloading. */
345 for (Sone knownSone : knownSones) {
346 core.addSone(knownSone);
349 } catch (IOException ioe1) {
350 logger.log(Level.WARNING, "Could not read XML file from " + originalSone + "!", ioe1);
353 if (xmlBucket != null) {
356 Closer.close(xmlInputStream);
369 protected void serviceStop() {
370 for (Sone sone : sones) {
371 freenetInterface.unregisterUsk(sone);