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 static java.lang.String.format;
21 import static java.lang.System.currentTimeMillis;
22 import static java.util.concurrent.TimeUnit.DAYS;
24 import java.io.InputStream;
25 import java.net.MalformedURLException;
26 import java.util.ArrayList;
27 import java.util.HashSet;
28 import java.util.List;
30 import java.util.concurrent.TimeUnit;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.FreenetInterface.Fetched;
35 import net.pterodactylus.sone.data.Album;
36 import net.pterodactylus.sone.data.Client;
37 import net.pterodactylus.sone.data.Image;
38 import net.pterodactylus.sone.data.Post;
39 import net.pterodactylus.sone.data.PostReply;
40 import net.pterodactylus.sone.data.Profile;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.data.Sone.SoneStatus;
43 import net.pterodactylus.sone.data.SoneImpl;
44 import net.pterodactylus.sone.database.PostBuilder;
45 import net.pterodactylus.sone.database.PostReplyBuilder;
46 import net.pterodactylus.util.io.Closer;
47 import net.pterodactylus.util.logging.Logging;
48 import net.pterodactylus.util.number.Numbers;
49 import net.pterodactylus.util.service.AbstractService;
50 import net.pterodactylus.util.xml.SimpleXML;
51 import net.pterodactylus.util.xml.XML;
53 import freenet.client.FetchResult;
54 import freenet.client.async.ClientContext;
55 import freenet.client.async.USKCallback;
56 import freenet.keys.FreenetURI;
57 import freenet.keys.USK;
58 import freenet.node.RequestStarter;
59 import freenet.support.api.Bucket;
61 import com.db4o.ObjectContainer;
63 import com.google.common.annotations.VisibleForTesting;
64 import org.w3c.dom.Document;
67 * The Sone downloader is responsible for download Sones as they are updated.
69 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
71 public class SoneDownloaderImpl extends AbstractService implements SoneDownloader {
74 private static final Logger logger = Logging.getLogger(SoneDownloaderImpl.class);
76 /** The maximum protocol version. */
77 private static final int MAX_PROTOCOL_VERSION = 0;
80 private final Core core;
82 /** The Freenet interface. */
83 private final FreenetInterface freenetInterface;
85 /** The sones to update. */
86 private final Set<Sone> sones = new HashSet<Sone>();
89 * Creates a new Sone downloader.
93 * @param freenetInterface
94 * The Freenet interface
96 public SoneDownloaderImpl(Core core, FreenetInterface freenetInterface) {
97 super("Sone Downloader", false);
99 this.freenetInterface = freenetInterface;
107 * Adds the given Sone to the set of Sones that will be watched for updates.
113 public void addSone(final Sone sone) {
114 if (!sones.add(sone)) {
115 freenetInterface.unregisterUsk(sone);
117 final USKCallback uskCallback = new USKCallback() {
120 @SuppressWarnings("synthetic-access")
121 public void onFoundEdition(long edition, USK key,
122 ObjectContainer objectContainer,
123 ClientContext clientContext, boolean metadata,
124 short codec, byte[] data, boolean newKnownGood,
125 boolean newSlotToo) {
126 logger.log(Level.FINE, format(
127 "Found USK update for Sone “%s” at %s, new known good: %s, new slot too: %s.",
128 sone, key, newKnownGood, newSlotToo));
129 if (edition > sone.getLatestEdition()) {
130 sone.setLatestEdition(edition);
131 new Thread(fetchSoneAction(sone),
132 "Sone Downloader").start();
137 public short getPollingPriorityProgress() {
138 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
142 public short getPollingPriorityNormal() {
143 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
146 if (soneHasBeenActiveRecently(sone)) {
147 freenetInterface.registerActiveUsk(sone.getRequestUri(),
150 freenetInterface.registerPassiveUsk(sone.getRequestUri(),
155 private boolean soneHasBeenActiveRecently(Sone sone) {
156 return (currentTimeMillis() - sone.getTime()) < DAYS.toMillis(7);
159 private void fetchSone(Sone sone) {
160 fetchSone(sone, sone.getRequestUri().sskForUSK());
164 * Fetches the updated Sone. This method can be used to fetch a Sone from a
170 * The URI to fetch the Sone from
173 public void fetchSone(Sone sone, FreenetURI soneUri) {
174 fetchSone(sone, soneUri, false);
178 * Fetches the Sone from the given URI.
183 * The URI of the Sone to fetch
185 * {@code true} to only fetch and parse the Sone, {@code false}
186 * to {@link Core#updateSone(Sone) update} it in the core
187 * @return The downloaded Sone, or {@code null} if the Sone could not be
191 public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
192 logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri));
193 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
194 sone.setStatus(SoneStatus.downloading);
196 Fetched fetchResults = freenetInterface.fetchUri(requestUri);
197 if (fetchResults == null) {
198 /* TODO - mark Sone as bad. */
201 logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
202 Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
203 if (parsedSone != null) {
205 parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
206 core.updateSone(parsedSone);
212 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
217 * Parses a Sone from a fetch result.
219 * @param originalSone
220 * The sone to parse, or {@code null} if the Sone is yet unknown
225 * @return The parsed Sone, or {@code null} if the Sone could not be parsed
227 private Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
228 logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone));
229 Bucket soneBucket = fetchResult.asBucket();
230 InputStream soneInputStream = null;
232 soneInputStream = soneBucket.getInputStream();
233 Sone parsedSone = parseSone(originalSone, soneInputStream);
234 if (parsedSone != null) {
235 parsedSone.setLatestEdition(requestUri.getEdition());
236 if (requestUri.getKeyType().equals("USK")) {
237 parsedSone.setRequestUri(requestUri.setMetaString(new String[0]));
239 parsedSone.setRequestUri(requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]));
243 } catch (Exception e1) {
244 logger.log(Level.WARNING, String.format("Could not parse Sone from %s!", requestUri), e1);
246 Closer.close(soneInputStream);
253 * Parses a Sone from the given input stream and creates a new Sone from the
256 * @param originalSone
258 * @param soneInputStream
259 * The input stream to parse the Sone from
260 * @return The parsed Sone
261 * @throws SoneException
262 * if a parse error occurs, or the protocol is invalid
265 protected Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
266 /* TODO - impose a size limit? */
269 /* XML parsing is not thread-safe. */
270 synchronized (this) {
271 document = XML.transformToDocument(soneInputStream);
273 if (document == null) {
274 /* TODO - mark Sone as bad. */
275 logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
279 Sone sone = new SoneImpl(originalSone.getId(), originalSone.isLocal()).setIdentity(originalSone.getIdentity());
283 soneXml = SimpleXML.fromDocument(document);
284 } catch (NullPointerException npe1) {
285 /* for some reason, invalid XML can cause NPEs. */
286 logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1);
290 Integer protocolVersion = null;
291 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
292 if (soneProtocolVersion != null) {
293 protocolVersion = Numbers.safeParseInteger(soneProtocolVersion);
295 if (protocolVersion == null) {
296 logger.log(Level.INFO, "No protocol version found, assuming 0.");
300 if (protocolVersion < 0) {
301 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
305 /* check for valid versions. */
306 if (protocolVersion > MAX_PROTOCOL_VERSION) {
307 logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
311 String soneTime = soneXml.getValue("time", null);
312 if (soneTime == null) {
313 /* TODO - mark Sone as bad. */
314 logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
318 sone.setTime(Long.parseLong(soneTime));
319 } catch (NumberFormatException nfe1) {
320 /* TODO - mark Sone as bad. */
321 logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
325 SimpleXML clientXml = soneXml.getNode("client");
326 if (clientXml != null) {
327 String clientName = clientXml.getValue("name", null);
328 String clientVersion = clientXml.getValue("version", null);
329 if ((clientName == null) || (clientVersion == null)) {
330 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
333 sone.setClient(new Client(clientName, clientVersion));
336 String soneRequestUri = soneXml.getValue("request-uri", null);
337 if (soneRequestUri != null) {
339 sone.setRequestUri(new FreenetURI(soneRequestUri));
340 } catch (MalformedURLException mue1) {
341 /* TODO - mark Sone as bad. */
342 logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid request URI: %s", sone, soneRequestUri), mue1);
347 if (originalSone.getInsertUri() != null) {
348 sone.setInsertUri(originalSone.getInsertUri());
351 SimpleXML profileXml = soneXml.getNode("profile");
352 if (profileXml == null) {
353 /* TODO - mark Sone as bad. */
354 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
359 String profileFirstName = profileXml.getValue("first-name", null);
360 String profileMiddleName = profileXml.getValue("middle-name", null);
361 String profileLastName = profileXml.getValue("last-name", null);
362 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
363 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
364 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
365 Profile profile = new Profile(sone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
366 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
367 /* avatar is processed after images are loaded. */
368 String avatarId = profileXml.getValue("avatar", null);
370 /* parse profile fields. */
371 SimpleXML profileFieldsXml = profileXml.getNode("fields");
372 if (profileFieldsXml != null) {
373 for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
374 String fieldName = fieldXml.getValue("field-name", null);
375 String fieldValue = fieldXml.getValue("field-value", "");
376 if (fieldName == null) {
377 logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
381 profile.addField(fieldName.trim()).setValue(fieldValue);
382 } catch (IllegalArgumentException iae1) {
383 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
390 SimpleXML postsXml = soneXml.getNode("posts");
391 Set<Post> posts = new HashSet<Post>();
392 if (postsXml == null) {
393 /* TODO - mark Sone as bad. */
394 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
396 for (SimpleXML postXml : postsXml.getNodes("post")) {
397 String postId = postXml.getValue("id", null);
398 String postRecipientId = postXml.getValue("recipient", null);
399 String postTime = postXml.getValue("time", null);
400 String postText = postXml.getValue("text", null);
401 if ((postId == null) || (postTime == null) || (postText == null)) {
402 /* TODO - mark Sone as bad. */
403 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
407 PostBuilder postBuilder = core.postBuilder();
408 /* TODO - parse time correctly. */
409 postBuilder.withId(postId).from(sone.getId()).withTime(Long.parseLong(postTime)).withText(postText);
410 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
411 postBuilder.to(postRecipientId);
413 posts.add(postBuilder.build());
414 } catch (NumberFormatException nfe1) {
415 /* TODO - mark Sone as bad. */
416 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
423 SimpleXML repliesXml = soneXml.getNode("replies");
424 Set<PostReply> replies = new HashSet<PostReply>();
425 if (repliesXml == null) {
426 /* TODO - mark Sone as bad. */
427 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
429 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
430 String replyId = replyXml.getValue("id", null);
431 String replyPostId = replyXml.getValue("post-id", null);
432 String replyTime = replyXml.getValue("time", null);
433 String replyText = replyXml.getValue("text", null);
434 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
435 /* TODO - mark Sone as bad. */
436 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));
440 PostReplyBuilder postReplyBuilder = core.postReplyBuilder();
441 /* TODO - parse time correctly. */
442 postReplyBuilder.withId(replyId).from(sone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText);
443 replies.add(postReplyBuilder.build());
444 } catch (NumberFormatException nfe1) {
445 /* TODO - mark Sone as bad. */
446 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
452 /* parse liked post IDs. */
453 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
454 Set<String> likedPostIds = new HashSet<String>();
455 if (likePostIdsXml == null) {
456 /* TODO - mark Sone as bad. */
457 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
459 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
460 String postId = likedPostIdXml.getValue();
461 likedPostIds.add(postId);
465 /* parse liked reply IDs. */
466 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
467 Set<String> likedReplyIds = new HashSet<String>();
468 if (likeReplyIdsXml == null) {
469 /* TODO - mark Sone as bad. */
470 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
472 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
473 String replyId = likedReplyIdXml.getValue();
474 likedReplyIds.add(replyId);
479 SimpleXML albumsXml = soneXml.getNode("albums");
480 List<Album> topLevelAlbums = new ArrayList<Album>();
481 if (albumsXml != null) {
482 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
483 String id = albumXml.getValue("id", null);
484 String parentId = albumXml.getValue("parent", null);
485 String title = albumXml.getValue("title", null);
486 String description = albumXml.getValue("description", "");
487 String albumImageId = albumXml.getValue("album-image", null);
488 if ((id == null) || (title == null)) {
489 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
493 if (parentId != null) {
494 parent = core.getAlbum(parentId);
495 if (parent == null) {
496 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
500 Album album = core.albumBuilder()
506 .setDescription(description)
508 if (parent != null) {
509 parent.addAlbum(album);
511 topLevelAlbums.add(album);
513 SimpleXML imagesXml = albumXml.getNode("images");
514 if (imagesXml != null) {
515 for (SimpleXML imageXml : imagesXml.getNodes("image")) {
516 String imageId = imageXml.getValue("id", null);
517 String imageCreationTimeString = imageXml.getValue("creation-time", null);
518 String imageKey = imageXml.getValue("key", null);
519 String imageTitle = imageXml.getValue("title", null);
520 String imageDescription = imageXml.getValue("description", "");
521 String imageWidthString = imageXml.getValue("width", null);
522 String imageHeightString = imageXml.getValue("height", null);
523 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
524 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
527 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
528 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
529 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
530 if ((imageWidth < 1) || (imageHeight < 1)) {
531 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
534 Image image = core.imageBuilder().withId(imageId).build().modify().setSone(sone).setKey(imageKey).setCreationTime(creationTime).update();
535 image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
536 image = image.modify().setWidth(imageWidth).setHeight(imageHeight).update();
537 album.addImage(image);
540 album.modify().setAlbumImage(albumImageId).update();
544 /* process avatar. */
545 if (avatarId != null) {
546 profile.setAvatar(core.getImage(avatarId, false));
549 /* okay, apparently everything was parsed correctly. Now import. */
550 /* atomic setter operation on the Sone. */
551 synchronized (sone) {
552 sone.setProfile(profile);
553 sone.setPosts(posts);
554 sone.setReplies(replies);
555 sone.setLikePostIds(likedPostIds);
556 sone.setLikeReplyIds(likedReplyIds);
557 for (Album album : topLevelAlbums) {
558 sone.getRootAlbum().addAlbum(album);
566 public Runnable fetchSoneWithUriAction(final Sone sone) {
567 return new Runnable() {
570 fetchSone(sone, sone.getRequestUri());
576 public Runnable fetchSoneAction(final Sone sone) {
577 return new Runnable() {
587 protected void serviceStop() {
588 for (Sone sone : sones) {
589 freenetInterface.unregisterUsk(sone);