2 * Sone - SoneDownloader.java - Copyright © 2010–2013 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.InputStream;
21 import java.net.MalformedURLException;
22 import java.util.ArrayList;
23 import java.util.HashSet;
24 import java.util.List;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
29 import net.pterodactylus.sone.core.FreenetInterface.Fetched;
30 import net.pterodactylus.sone.data.Album;
31 import net.pterodactylus.sone.data.Client;
32 import net.pterodactylus.sone.data.Image;
33 import net.pterodactylus.sone.data.Post;
34 import net.pterodactylus.sone.data.PostReply;
35 import net.pterodactylus.sone.data.Profile;
36 import net.pterodactylus.sone.data.Sone;
37 import net.pterodactylus.sone.data.Sone.SoneStatus;
38 import net.pterodactylus.sone.database.PostBuilder;
39 import net.pterodactylus.sone.database.PostReplyBuilder;
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().sskForUSK());
130 * Fetches the updated Sone. This method can be used to fetch a Sone from a
136 * The URI to fetch the Sone from
138 public void fetchSone(Sone sone, FreenetURI soneUri) {
139 fetchSone(sone, soneUri, false);
143 * Fetches the Sone from the given URI.
148 * The URI of the Sone to fetch
150 * {@code true} to only fetch and parse the Sone, {@code false}
151 * to {@link Core#updateSone(Sone) update} it in the core
152 * @return The downloaded Sone, or {@code null} if the Sone could not be
155 public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
156 logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri));
157 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
158 sone.setStatus(SoneStatus.downloading);
160 Fetched fetchResults = freenetInterface.fetchUri(requestUri);
161 if (fetchResults == null) {
162 /* TODO - mark Sone as bad. */
165 logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
166 Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
167 if (parsedSone != null) {
169 parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
170 core.updateSone(parsedSone);
176 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
181 * Parses a Sone from a fetch result.
183 * @param originalSone
184 * The sone to parse, or {@code null} if the Sone is yet unknown
189 * @return The parsed Sone, or {@code null} if the Sone could not be parsed
191 public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
192 logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone));
193 Bucket soneBucket = fetchResult.asBucket();
194 InputStream soneInputStream = null;
196 soneInputStream = soneBucket.getInputStream();
197 Sone parsedSone = parseSone(originalSone, soneInputStream);
198 if (parsedSone != null) {
199 parsedSone.setLatestEdition(requestUri.getEdition());
200 if (requestUri.getKeyType().equals("USK")) {
201 parsedSone.setRequestUri(requestUri.setMetaString(new String[0]));
203 parsedSone.setRequestUri(requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]));
207 } catch (Exception e1) {
208 logger.log(Level.WARNING, String.format("Could not parse Sone from %s!", requestUri), e1);
210 Closer.close(soneInputStream);
217 * Parses a Sone from the given input stream and creates a new Sone from the
220 * @param originalSone
222 * @param soneInputStream
223 * The input stream to parse the Sone from
224 * @return The parsed Sone
225 * @throws SoneException
226 * if a parse error occurs, or the protocol is invalid
228 public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
229 /* TODO - impose a size limit? */
232 /* XML parsing is not thread-safe. */
233 synchronized (this) {
234 document = XML.transformToDocument(soneInputStream);
236 if (document == null) {
237 /* TODO - mark Sone as bad. */
238 logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
242 Sone sone = new Sone(originalSone.getId(), false).setIdentity(originalSone.getIdentity());
246 soneXml = SimpleXML.fromDocument(document);
247 } catch (NullPointerException npe1) {
248 /* for some reason, invalid XML can cause NPEs. */
249 logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1);
253 Integer protocolVersion = null;
254 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
255 if (soneProtocolVersion != null) {
256 protocolVersion = Numbers.safeParseInteger(soneProtocolVersion);
258 if (protocolVersion == null) {
259 logger.log(Level.INFO, "No protocol version found, assuming 0.");
263 if (protocolVersion < 0) {
264 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
268 /* check for valid versions. */
269 if (protocolVersion > MAX_PROTOCOL_VERSION) {
270 logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
274 String soneTime = soneXml.getValue("time", null);
275 if (soneTime == null) {
276 /* TODO - mark Sone as bad. */
277 logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
281 sone.setTime(Long.parseLong(soneTime));
282 } catch (NumberFormatException nfe1) {
283 /* TODO - mark Sone as bad. */
284 logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
288 SimpleXML clientXml = soneXml.getNode("client");
289 if (clientXml != null) {
290 String clientName = clientXml.getValue("name", null);
291 String clientVersion = clientXml.getValue("version", null);
292 if ((clientName == null) || (clientVersion == null)) {
293 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
296 sone.setClient(new Client(clientName, clientVersion));
299 String soneRequestUri = soneXml.getValue("request-uri", null);
300 if (soneRequestUri != null) {
302 sone.setRequestUri(new FreenetURI(soneRequestUri));
303 } catch (MalformedURLException mue1) {
304 /* TODO - mark Sone as bad. */
305 logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid request URI: %s", sone, soneRequestUri), mue1);
310 String soneInsertUri = soneXml.getValue("insert-uri", null);
311 if ((soneInsertUri != null) && (sone.getInsertUri() == null)) {
313 sone.setInsertUri(new FreenetURI(soneInsertUri));
314 sone.setLatestEdition(Math.max(sone.getRequestUri().getEdition(), sone.getInsertUri().getEdition()));
315 } catch (MalformedURLException mue1) {
316 /* TODO - mark Sone as bad. */
317 logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid insert URI: %s", sone, soneInsertUri), mue1);
322 SimpleXML profileXml = soneXml.getNode("profile");
323 if (profileXml == null) {
324 /* TODO - mark Sone as bad. */
325 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
330 String profileFirstName = profileXml.getValue("first-name", null);
331 String profileMiddleName = profileXml.getValue("middle-name", null);
332 String profileLastName = profileXml.getValue("last-name", null);
333 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
334 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
335 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
336 Profile profile = new Profile(sone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
337 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
338 /* avatar is processed after images are loaded. */
339 String avatarId = profileXml.getValue("avatar", null);
341 /* parse profile fields. */
342 SimpleXML profileFieldsXml = profileXml.getNode("fields");
343 if (profileFieldsXml != null) {
344 for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
345 String fieldName = fieldXml.getValue("field-name", null);
346 String fieldValue = fieldXml.getValue("field-value", "");
347 if (fieldName == null) {
348 logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
352 profile.addField(fieldName).setValue(fieldValue);
353 } catch (IllegalArgumentException iae1) {
354 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
361 SimpleXML postsXml = soneXml.getNode("posts");
362 Set<Post> posts = new HashSet<Post>();
363 if (postsXml == null) {
364 /* TODO - mark Sone as bad. */
365 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
367 for (SimpleXML postXml : postsXml.getNodes("post")) {
368 String postId = postXml.getValue("id", null);
369 String postRecipientId = postXml.getValue("recipient", null);
370 String postTime = postXml.getValue("time", null);
371 String postText = postXml.getValue("text", null);
372 if ((postId == null) || (postTime == null) || (postText == null)) {
373 /* TODO - mark Sone as bad. */
374 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
378 PostBuilder postBuilder = core.postBuilder();
379 /* TODO - parse time correctly. */
380 postBuilder.withId(postId).from(sone.getId()).withTime(Long.parseLong(postTime)).withText(postText);
381 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
382 postBuilder.to(postRecipientId);
384 posts.add(postBuilder.build());
385 } catch (NumberFormatException nfe1) {
386 /* TODO - mark Sone as bad. */
387 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
394 SimpleXML repliesXml = soneXml.getNode("replies");
395 Set<PostReply> replies = new HashSet<PostReply>();
396 if (repliesXml == null) {
397 /* TODO - mark Sone as bad. */
398 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
400 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
401 String replyId = replyXml.getValue("id", null);
402 String replyPostId = replyXml.getValue("post-id", null);
403 String replyTime = replyXml.getValue("time", null);
404 String replyText = replyXml.getValue("text", null);
405 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
406 /* TODO - mark Sone as bad. */
407 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with missing data! ID: %s, Post: %s, Time: %s, Text: %s", sone, replyId, replyPostId, replyTime, replyText));
411 PostReplyBuilder postReplyBuilder = core.postReplyBuilder();
412 /* TODO - parse time correctly. */
413 postReplyBuilder.withId(replyId).from(sone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText);
414 replies.add(postReplyBuilder.build());
415 } catch (NumberFormatException nfe1) {
416 /* TODO - mark Sone as bad. */
417 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
423 /* parse liked post IDs. */
424 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
425 Set<String> likedPostIds = new HashSet<String>();
426 if (likePostIdsXml == null) {
427 /* TODO - mark Sone as bad. */
428 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
430 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
431 String postId = likedPostIdXml.getValue();
432 likedPostIds.add(postId);
436 /* parse liked reply IDs. */
437 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
438 Set<String> likedReplyIds = new HashSet<String>();
439 if (likeReplyIdsXml == null) {
440 /* TODO - mark Sone as bad. */
441 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
443 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
444 String replyId = likedReplyIdXml.getValue();
445 likedReplyIds.add(replyId);
450 SimpleXML albumsXml = soneXml.getNode("albums");
451 List<Album> topLevelAlbums = new ArrayList<Album>();
452 if (albumsXml != null) {
453 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
454 String id = albumXml.getValue("id", null);
455 String parentId = albumXml.getValue("parent", null);
456 String title = albumXml.getValue("title", null);
457 String description = albumXml.getValue("description", "");
458 String albumImageId = albumXml.getValue("album-image", null);
459 if ((id == null) || (title == null) || (description == null)) {
460 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
464 if (parentId != null) {
465 parent = core.getAlbum(parentId, false);
466 if (parent == null) {
467 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
471 Album album = core.getAlbum(id).setSone(sone).setTitle(title).setDescription(description);
472 if (parent != null) {
473 parent.addAlbum(album);
475 topLevelAlbums.add(album);
477 SimpleXML imagesXml = albumXml.getNode("images");
478 if (imagesXml != null) {
479 for (SimpleXML imageXml : imagesXml.getNodes("image")) {
480 String imageId = imageXml.getValue("id", null);
481 String imageCreationTimeString = imageXml.getValue("creation-time", null);
482 String imageKey = imageXml.getValue("key", null);
483 String imageTitle = imageXml.getValue("title", null);
484 String imageDescription = imageXml.getValue("description", "");
485 String imageWidthString = imageXml.getValue("width", null);
486 String imageHeightString = imageXml.getValue("height", null);
487 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
488 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
491 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
492 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
493 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
494 if ((imageWidth < 1) || (imageHeight < 1)) {
495 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
498 Image image = core.getImage(imageId).setSone(sone).setKey(imageKey).setCreationTime(creationTime);
499 image.setTitle(imageTitle).setDescription(imageDescription);
500 image.setWidth(imageWidth).setHeight(imageHeight);
501 album.addImage(image);
504 album.setAlbumImage(albumImageId);
508 /* process avatar. */
509 if (avatarId != null) {
510 profile.setAvatar(core.getImage(avatarId, false));
513 /* okay, apparently everything was parsed correctly. Now import. */
514 /* atomic setter operation on the Sone. */
515 synchronized (sone) {
516 sone.setProfile(profile);
517 sone.setPosts(posts);
518 sone.setReplies(replies);
519 sone.setLikePostIds(likedPostIds);
520 sone.setLikeReplyIds(likedReplyIds);
521 sone.setAlbums(topLevelAlbums);
535 protected void serviceStop() {
536 for (Sone sone : sones) {
537 freenetInterface.unregisterUsk(sone);