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.registerUsk(sone, this);
106 * Removes the given Sone from the downloader.
109 * The Sone to stop watching
111 public void removeSone(Sone sone) {
112 if (sones.remove(sone)) {
113 freenetInterface.unregisterUsk(sone);
118 * Fetches the updated Sone. This method is a callback method for
119 * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
124 public void fetchSone(Sone sone) {
125 fetchSone(sone, sone.getRequestUri().sskForUSK());
129 * Fetches the updated Sone. This method can be used to fetch a Sone from a
135 * The URI to fetch the Sone from
137 public void fetchSone(Sone sone, FreenetURI soneUri) {
138 fetchSone(sone, soneUri, false);
142 * Fetches the Sone from the given URI.
147 * The URI of the Sone to fetch
149 * {@code true} to only fetch and parse the Sone, {@code false}
150 * to {@link Core#updateSone(Sone) update} it in the core
151 * @return The downloaded Sone, or {@code null} if the Sone could not be
154 public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
155 logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri));
156 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
157 sone.setStatus(SoneStatus.downloading);
159 Fetched fetchResults = freenetInterface.fetchUri(requestUri);
160 if (fetchResults == null) {
161 /* TODO - mark Sone as bad. */
164 logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
165 Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
166 if (parsedSone != null) {
168 parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
169 core.updateSone(parsedSone);
175 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
180 * Parses a Sone from a fetch result.
182 * @param originalSone
183 * The sone to parse, or {@code null} if the Sone is yet unknown
188 * @return The parsed Sone, or {@code null} if the Sone could not be parsed
190 public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
191 logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone));
192 Bucket soneBucket = fetchResult.asBucket();
193 InputStream soneInputStream = null;
195 soneInputStream = soneBucket.getInputStream();
196 Sone parsedSone = parseSone(originalSone, soneInputStream);
197 if (parsedSone != null) {
198 parsedSone.setLatestEdition(requestUri.getEdition());
199 if (requestUri.getKeyType().equals("USK")) {
200 parsedSone.setRequestUri(requestUri.setMetaString(new String[0]));
202 parsedSone.setRequestUri(requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]));
206 } catch (Exception e1) {
207 logger.log(Level.WARNING, String.format("Could not parse Sone from %s!", requestUri), e1);
209 Closer.close(soneInputStream);
216 * Parses a Sone from the given input stream and creates a new Sone from the
219 * @param originalSone
221 * @param soneInputStream
222 * The input stream to parse the Sone from
223 * @return The parsed Sone
224 * @throws SoneException
225 * if a parse error occurs, or the protocol is invalid
227 public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
228 /* TODO - impose a size limit? */
231 /* XML parsing is not thread-safe. */
232 synchronized (this) {
233 document = XML.transformToDocument(soneInputStream);
235 if (document == null) {
236 /* TODO - mark Sone as bad. */
237 logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
241 Sone sone = new Sone(originalSone.getId(), false).setIdentity(originalSone.getIdentity());
245 soneXml = SimpleXML.fromDocument(document);
246 } catch (NullPointerException npe1) {
247 /* for some reason, invalid XML can cause NPEs. */
248 logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1);
252 Integer protocolVersion = null;
253 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
254 if (soneProtocolVersion != null) {
255 protocolVersion = Numbers.safeParseInteger(soneProtocolVersion);
257 if (protocolVersion == null) {
258 logger.log(Level.INFO, "No protocol version found, assuming 0.");
262 if (protocolVersion < 0) {
263 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
267 /* check for valid versions. */
268 if (protocolVersion > MAX_PROTOCOL_VERSION) {
269 logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
273 String soneTime = soneXml.getValue("time", null);
274 if (soneTime == null) {
275 /* TODO - mark Sone as bad. */
276 logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
280 sone.setTime(Long.parseLong(soneTime));
281 } catch (NumberFormatException nfe1) {
282 /* TODO - mark Sone as bad. */
283 logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
287 SimpleXML clientXml = soneXml.getNode("client");
288 if (clientXml != null) {
289 String clientName = clientXml.getValue("name", null);
290 String clientVersion = clientXml.getValue("version", null);
291 if ((clientName == null) || (clientVersion == null)) {
292 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
295 sone.setClient(new Client(clientName, clientVersion));
298 String soneRequestUri = soneXml.getValue("request-uri", null);
299 if (soneRequestUri != null) {
301 sone.setRequestUri(new FreenetURI(soneRequestUri));
302 } catch (MalformedURLException mue1) {
303 /* TODO - mark Sone as bad. */
304 logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid request URI: %s", sone, soneRequestUri), mue1);
309 String soneInsertUri = soneXml.getValue("insert-uri", null);
310 if ((soneInsertUri != null) && (sone.getInsertUri() == null)) {
312 sone.setInsertUri(new FreenetURI(soneInsertUri));
313 sone.setLatestEdition(Math.max(sone.getRequestUri().getEdition(), sone.getInsertUri().getEdition()));
314 } catch (MalformedURLException mue1) {
315 /* TODO - mark Sone as bad. */
316 logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid insert URI: %s", sone, soneInsertUri), mue1);
321 SimpleXML profileXml = soneXml.getNode("profile");
322 if (profileXml == null) {
323 /* TODO - mark Sone as bad. */
324 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
329 String profileFirstName = profileXml.getValue("first-name", null);
330 String profileMiddleName = profileXml.getValue("middle-name", null);
331 String profileLastName = profileXml.getValue("last-name", null);
332 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
333 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
334 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
335 Profile profile = new Profile(sone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
336 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
337 /* avatar is processed after images are loaded. */
338 String avatarId = profileXml.getValue("avatar", null);
340 /* parse profile fields. */
341 SimpleXML profileFieldsXml = profileXml.getNode("fields");
342 if (profileFieldsXml != null) {
343 for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
344 String fieldName = fieldXml.getValue("field-name", null);
345 String fieldValue = fieldXml.getValue("field-value", "");
346 if (fieldName == null) {
347 logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
351 profile.addField(fieldName).setValue(fieldValue);
352 } catch (IllegalArgumentException iae1) {
353 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
360 SimpleXML postsXml = soneXml.getNode("posts");
361 Set<Post> posts = new HashSet<Post>();
362 if (postsXml == null) {
363 /* TODO - mark Sone as bad. */
364 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
366 for (SimpleXML postXml : postsXml.getNodes("post")) {
367 String postId = postXml.getValue("id", null);
368 String postRecipientId = postXml.getValue("recipient", null);
369 String postTime = postXml.getValue("time", null);
370 String postText = postXml.getValue("text", null);
371 if ((postId == null) || (postTime == null) || (postText == null)) {
372 /* TODO - mark Sone as bad. */
373 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
377 PostBuilder postBuilder = core.postBuilder();
378 /* TODO - parse time correctly. */
379 postBuilder.withId(postId).from(sone.getId()).withTime(Long.parseLong(postTime)).withText(postText);
380 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
381 postBuilder.to(postRecipientId);
383 posts.add(postBuilder.build());
384 } catch (NumberFormatException nfe1) {
385 /* TODO - mark Sone as bad. */
386 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
393 SimpleXML repliesXml = soneXml.getNode("replies");
394 Set<PostReply> replies = new HashSet<PostReply>();
395 if (repliesXml == null) {
396 /* TODO - mark Sone as bad. */
397 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
399 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
400 String replyId = replyXml.getValue("id", null);
401 String replyPostId = replyXml.getValue("post-id", null);
402 String replyTime = replyXml.getValue("time", null);
403 String replyText = replyXml.getValue("text", null);
404 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
405 /* TODO - mark Sone as bad. */
406 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));
410 PostReplyBuilder postReplyBuilder = core.postReplyBuilder();
411 /* TODO - parse time correctly. */
412 postReplyBuilder.withId(replyId).from(sone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText);
413 replies.add(postReplyBuilder.build());
414 } catch (NumberFormatException nfe1) {
415 /* TODO - mark Sone as bad. */
416 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
422 /* parse liked post IDs. */
423 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
424 Set<String> likedPostIds = new HashSet<String>();
425 if (likePostIdsXml == null) {
426 /* TODO - mark Sone as bad. */
427 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
429 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
430 String postId = likedPostIdXml.getValue();
431 likedPostIds.add(postId);
435 /* parse liked reply IDs. */
436 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
437 Set<String> likedReplyIds = new HashSet<String>();
438 if (likeReplyIdsXml == null) {
439 /* TODO - mark Sone as bad. */
440 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
442 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
443 String replyId = likedReplyIdXml.getValue();
444 likedReplyIds.add(replyId);
449 SimpleXML albumsXml = soneXml.getNode("albums");
450 List<Album> topLevelAlbums = new ArrayList<Album>();
451 if (albumsXml != null) {
452 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
453 String id = albumXml.getValue("id", null);
454 String parentId = albumXml.getValue("parent", null);
455 String title = albumXml.getValue("title", null);
456 String description = albumXml.getValue("description", "");
457 String albumImageId = albumXml.getValue("album-image", null);
458 if ((id == null) || (title == null) || (description == null)) {
459 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
463 if (parentId != null) {
464 parent = core.getAlbum(parentId, false);
465 if (parent == null) {
466 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
470 Album album = core.getAlbum(id).setSone(sone).setTitle(title).setDescription(description);
471 if (parent != null) {
472 parent.addAlbum(album);
474 topLevelAlbums.add(album);
476 SimpleXML imagesXml = albumXml.getNode("images");
477 if (imagesXml != null) {
478 for (SimpleXML imageXml : imagesXml.getNodes("image")) {
479 String imageId = imageXml.getValue("id", null);
480 String imageCreationTimeString = imageXml.getValue("creation-time", null);
481 String imageKey = imageXml.getValue("key", null);
482 String imageTitle = imageXml.getValue("title", null);
483 String imageDescription = imageXml.getValue("description", "");
484 String imageWidthString = imageXml.getValue("width", null);
485 String imageHeightString = imageXml.getValue("height", null);
486 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
487 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
490 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
491 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
492 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
493 if ((imageWidth < 1) || (imageHeight < 1)) {
494 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
497 Image image = core.getImage(imageId).setSone(sone).setKey(imageKey).setCreationTime(creationTime);
498 image.setTitle(imageTitle).setDescription(imageDescription);
499 image.setWidth(imageWidth).setHeight(imageHeight);
500 album.addImage(image);
503 album.setAlbumImage(albumImageId);
507 /* process avatar. */
508 if (avatarId != null) {
509 profile.setAvatar(core.getImage(avatarId, false));
512 /* okay, apparently everything was parsed correctly. Now import. */
513 /* atomic setter operation on the Sone. */
514 synchronized (sone) {
515 sone.setProfile(profile);
516 sone.setPosts(posts);
517 sone.setReplies(replies);
518 sone.setLikePostIds(likedPostIds);
519 sone.setLikeReplyIds(likedReplyIds);
520 sone.setAlbums(topLevelAlbums);
534 protected void serviceStop() {
535 for (Sone sone : sones) {
536 freenetInterface.unregisterUsk(sone);