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.ArrayList;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
30 import net.pterodactylus.sone.core.Core.Preferences;
31 import net.pterodactylus.sone.core.Core.SoneStatus;
32 import net.pterodactylus.sone.data.Album;
33 import net.pterodactylus.sone.data.Client;
34 import net.pterodactylus.sone.data.Image;
35 import net.pterodactylus.sone.data.Post;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Reply;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.util.collection.Pair;
40 import net.pterodactylus.util.io.Closer;
41 import net.pterodactylus.util.logging.Logging;
42 import net.pterodactylus.util.number.Numbers;
43 import net.pterodactylus.util.service.AbstractService;
44 import net.pterodactylus.util.xml.SimpleXML;
45 import net.pterodactylus.util.xml.XML;
47 import org.w3c.dom.Document;
49 import freenet.client.FetchResult;
50 import freenet.keys.FreenetURI;
51 import freenet.support.api.Bucket;
54 * The Sone downloader is responsible for download Sones as they are updated.
56 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
58 public class SoneDownloader extends AbstractService {
61 private static final Logger logger = Logging.getLogger(SoneDownloader.class);
63 /** The maximum protocol version. */
64 private static final int MAX_PROTOCOL_VERSION = 0;
67 private final Core core;
69 /** The Freenet interface. */
70 private final FreenetInterface freenetInterface;
72 /** The sones to update. */
73 private final Set<Sone> sones = new HashSet<Sone>();
76 * Creates a new Sone downloader.
80 * @param freenetInterface
81 * The Freenet interface
83 public SoneDownloader(Core core, FreenetInterface freenetInterface) {
84 super("Sone Downloader", false);
86 this.freenetInterface = freenetInterface;
94 * Adds the given Sone to the set of Sones that will be watched for updates.
99 public void addSone(Sone sone) {
100 if (!sones.add(sone)) {
101 freenetInterface.unregisterUsk(sone);
103 freenetInterface.registerUsk(sone, this);
107 * Removes the given Sone from the downloader.
110 * The Sone to stop watching
112 public void removeSone(Sone sone) {
113 if (sones.remove(sone)) {
114 freenetInterface.unregisterUsk(sone);
119 * Fetches the updated Sone. This method is a callback method for
120 * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
125 public void fetchSone(Sone sone) {
126 fetchSone(sone, sone.getRequestUri());
130 * Fetches the updated Sone. This method can be used to fetch a Sone from a
131 * specific URI (which happens when {@link Preferences#isSoneRescueMode()
132 * „Sone rescue mode“} is active).
137 * The URI to fetch the Sone from
139 public void fetchSone(Sone sone, FreenetURI soneUri) {
140 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, soneUri });
141 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
142 core.setSoneStatus(sone, SoneStatus.downloading);
144 Pair<FreenetURI, FetchResult> fetchResults = freenetInterface.fetchUri(requestUri);
145 if (fetchResults == null) {
146 /* TODO - mark Sone as bad. */
149 logger.log(Level.FINEST, "Got %d bytes back.", fetchResults.getRight().size());
150 Sone parsedSone = parseSone(sone, fetchResults.getRight(), fetchResults.getLeft());
151 if (parsedSone != null) {
153 core.updateSone(parsedSone);
156 core.setSoneStatus(sone, (sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
161 * Parses a Sone from a fetch result.
163 * @param originalSone
164 * The sone to parse, or {@code null} if the Sone is yet unknown
169 * @return The parsed Sone, or {@code null} if the Sone could not be parsed
171 public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
172 logger.log(Level.FINEST, "Parsing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), originalSone });
173 Bucket soneBucket = fetchResult.asBucket();
174 InputStream soneInputStream = null;
176 soneInputStream = soneBucket.getInputStream();
177 Sone parsedSone = parseSone(originalSone, soneInputStream);
178 if (parsedSone != null) {
179 parsedSone.setLatestEdition(requestUri.getEdition());
180 if (requestUri.getKeyType().equals("USK")) {
181 parsedSone.setRequestUri(requestUri.setMetaString(new String[0]));
183 parsedSone.setRequestUri(requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]));
187 } catch (IOException ioe1) {
188 logger.log(Level.WARNING, "Could not parse Sone from " + requestUri + "!", ioe1);
190 Closer.close(soneInputStream);
197 * Parses a Sone from the given input stream and creates a new Sone from the
200 * @param originalSone
202 * @param soneInputStream
203 * The input stream to parse the Sone from
204 * @return The parsed Sone
206 public Sone parseSone(Sone originalSone, InputStream soneInputStream) {
207 /* TODO - impose a size limit? */
210 /* XML parsing is not thread-safe. */
211 synchronized (this) {
212 document = XML.transformToDocument(soneInputStream);
214 if (document == null) {
215 /* TODO - mark Sone as bad. */
216 logger.log(Level.WARNING, "Could not parse XML for Sone %s!", new Object[] { originalSone });
220 Sone sone = new Sone(originalSone.getId()).setIdentity(originalSone.getIdentity());
224 soneXml = SimpleXML.fromDocument(document);
225 } catch (NullPointerException npe1) {
226 /* for some reason, invalid XML can cause NPEs. */
227 logger.log(Level.WARNING, "XML for Sone " + sone + " can not be parsed!", npe1);
231 Integer protocolVersion = null;
232 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
233 if (soneProtocolVersion != null) {
234 protocolVersion = Numbers.safeParseInteger(soneProtocolVersion);
236 if (protocolVersion == null) {
237 logger.log(Level.INFO, "No protocol version found, assuming 0.");
241 if (protocolVersion < 0) {
242 logger.log(Level.WARNING, "Invalid protocol version: " + protocolVersion + "! Not parsing Sone.");
246 /* check for valid versions. */
247 if (protocolVersion > MAX_PROTOCOL_VERSION) {
248 logger.log(Level.WARNING, "Unknown protocol version: " + protocolVersion + "! Not parsing Sone.");
252 String soneTime = soneXml.getValue("time", null);
253 if (soneTime == null) {
254 /* TODO - mark Sone as bad. */
255 logger.log(Level.WARNING, "Downloaded time for Sone %s was null!", new Object[] { sone });
259 sone.setTime(Long.parseLong(soneTime));
260 } catch (NumberFormatException nfe1) {
261 /* TODO - mark Sone as bad. */
262 logger.log(Level.WARNING, "Downloaded Sone %s with invalid time: %s", new Object[] { sone, soneTime });
266 SimpleXML clientXml = soneXml.getNode("client");
267 if (clientXml != null) {
268 String clientName = clientXml.getValue("name", null);
269 String clientVersion = clientXml.getValue("version", null);
270 if ((clientName == null) || (clientVersion == null)) {
271 logger.log(Level.WARNING, "Download Sone %s with client XML but missing name or version!", sone);
274 sone.setClient(new Client(clientName, clientVersion));
277 String soneRequestUri = soneXml.getValue("request-uri", null);
278 if (soneRequestUri != null) {
280 sone.setRequestUri(new FreenetURI(soneRequestUri));
281 } catch (MalformedURLException mue1) {
282 /* TODO - mark Sone as bad. */
283 logger.log(Level.WARNING, "Downloaded Sone " + sone + " has invalid request URI: " + soneRequestUri, mue1);
288 String soneInsertUri = soneXml.getValue("insert-uri", null);
289 if ((soneInsertUri != null) && (sone.getInsertUri() == null)) {
291 sone.setInsertUri(new FreenetURI(soneInsertUri));
292 sone.setLatestEdition(Math.max(sone.getRequestUri().getEdition(), sone.getInsertUri().getEdition()));
293 } catch (MalformedURLException mue1) {
294 /* TODO - mark Sone as bad. */
295 logger.log(Level.WARNING, "Downloaded Sone " + sone + " has invalid insert URI: " + soneInsertUri, mue1);
300 SimpleXML profileXml = soneXml.getNode("profile");
301 if (profileXml == null) {
302 /* TODO - mark Sone as bad. */
303 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
308 String profileFirstName = profileXml.getValue("first-name", null);
309 String profileMiddleName = profileXml.getValue("middle-name", null);
310 String profileLastName = profileXml.getValue("last-name", null);
311 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
312 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
313 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
314 Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
315 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
317 /* parse profile fields. */
318 SimpleXML profileFieldsXml = profileXml.getNode("fields");
319 if (profileFieldsXml != null) {
320 for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
321 String fieldName = fieldXml.getValue("field-name", null);
322 String fieldValue = fieldXml.getValue("field-value", null);
323 if ((fieldName == null) || (fieldValue == null)) {
324 logger.log(Level.WARNING, "Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", new Object[] { sone, fieldName, fieldValue });
328 profile.addField(fieldName).setValue(fieldValue);
329 } catch (IllegalArgumentException iae1) {
330 logger.log(Level.WARNING, "Duplicate field: " + fieldName, iae1);
337 SimpleXML postsXml = soneXml.getNode("posts");
338 Set<Post> posts = new HashSet<Post>();
339 if (postsXml == null) {
340 /* TODO - mark Sone as bad. */
341 logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
343 for (SimpleXML postXml : postsXml.getNodes("post")) {
344 String postId = postXml.getValue("id", null);
345 String postRecipientId = postXml.getValue("recipient", null);
346 String postTime = postXml.getValue("time", null);
347 String postText = postXml.getValue("text", null);
348 if ((postId == null) || (postTime == null) || (postText == null)) {
349 /* TODO - mark Sone as bad. */
350 logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
354 Post post = core.getPost(postId).setSone(sone).setTime(Long.parseLong(postTime)).setText(postText);
355 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
356 post.setRecipient(core.getSone(postRecipientId));
359 } catch (NumberFormatException nfe1) {
360 /* TODO - mark Sone as bad. */
361 logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
368 SimpleXML repliesXml = soneXml.getNode("replies");
369 Set<Reply> replies = new HashSet<Reply>();
370 if (repliesXml == null) {
371 /* TODO - mark Sone as bad. */
372 logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
374 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
375 String replyId = replyXml.getValue("id", null);
376 String replyPostId = replyXml.getValue("post-id", null);
377 String replyTime = replyXml.getValue("time", null);
378 String replyText = replyXml.getValue("text", null);
379 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
380 /* TODO - mark Sone as bad. */
381 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 });
385 replies.add(core.getReply(replyId).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
386 } catch (NumberFormatException nfe1) {
387 /* TODO - mark Sone as bad. */
388 logger.log(Level.WARNING, "Downloaded reply for Sone %s with invalid time: %s", new Object[] { sone, replyTime });
394 /* parse liked post IDs. */
395 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
396 Set<String> likedPostIds = new HashSet<String>();
397 if (likePostIdsXml == null) {
398 /* TODO - mark Sone as bad. */
399 logger.log(Level.WARNING, "Downloaded Sone %s has no post likes!", new Object[] { sone });
401 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
402 String postId = likedPostIdXml.getValue();
403 likedPostIds.add(postId);
407 /* parse liked reply IDs. */
408 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
409 Set<String> likedReplyIds = new HashSet<String>();
410 if (likeReplyIdsXml == null) {
411 /* TODO - mark Sone as bad. */
412 logger.log(Level.WARNING, "Downloaded Sone %s has no reply likes!", new Object[] { sone });
414 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
415 String replyId = likedReplyIdXml.getValue();
416 likedReplyIds.add(replyId);
421 SimpleXML albumsXml = soneXml.getNode("albums");
422 List<Album> topLevelAlbums = new ArrayList<Album>();
423 if (albumsXml != null) {
424 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
425 String id = albumXml.getValue("id", null);
426 String parentId = albumXml.getValue("parent", null);
427 String title = albumXml.getValue("title", null);
428 String description = albumXml.getValue("description", null);
429 if ((id == null) || (title == null) || (description == null)) {
430 logger.log(Level.WARNING, "Downloaded Sone %s contains invalid album!", new Object[] { sone });
434 if (parentId != null) {
435 parent = core.getAlbum(parentId, false);
436 if (parent == null) {
437 logger.log(Level.WARNING, "Downloaded Sone %s has album with invalid parent!", new Object[] { sone });
441 Album album = core.getAlbum(id).setSone(sone).setTitle(title).setDescription(description);
442 if (parent != null) {
443 parent.addAlbum(album);
445 topLevelAlbums.add(album);
447 SimpleXML imagesXml = albumXml.getNode("images");
448 if (imagesXml != null) {
449 for (SimpleXML imageXml : imagesXml.getNodes("image")) {
450 String imageId = imageXml.getValue("id", null);
451 String imageCreationTimeString = imageXml.getValue("creation-time", null);
452 String imageKey = imageXml.getValue("key", null);
453 String imageTitle = imageXml.getValue("title", null);
454 String imageDescription = imageXml.getValue("description", "");
455 String imageWidthString = imageXml.getValue("width", null);
456 String imageHeightString = imageXml.getValue("height", null);
457 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
458 logger.log(Level.WARNING, "Downloaded Sone %s contains invalid images!", new Object[] { sone });
461 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
462 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
463 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
464 if ((imageWidth < 1) || (imageHeight < 1)) {
465 logger.log(Level.WARNING, "Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", new Object[] { sone, imageId, imageWidthString, imageHeightString });
468 Image image = core.getImage(imageId).setSone(sone).setKey(imageKey).setCreationTime(creationTime);
469 image.setTitle(imageTitle).setDescription(imageDescription);
470 image.setWidth(imageWidth).setHeight(imageHeight);
471 album.addImage(image);
477 /* okay, apparently everything was parsed correctly. Now import. */
478 /* atomic setter operation on the Sone. */
479 synchronized (sone) {
480 sone.setProfile(profile);
481 sone.setPosts(posts);
482 sone.setReplies(replies);
483 sone.setLikePostIds(likedPostIds);
484 sone.setLikeReplyIds(likedReplyIds);
485 sone.setAlbums(topLevelAlbums);
499 protected void serviceStop() {
500 for (Sone sone : sones) {
501 freenetInterface.unregisterUsk(sone);