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.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.Core.SoneStatus;
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.Profile;
35 import net.pterodactylus.sone.data.Reply;
36 import net.pterodactylus.sone.data.Sone;
37 import net.pterodactylus.util.collection.Pair;
38 import net.pterodactylus.util.io.Closer;
39 import net.pterodactylus.util.logging.Logging;
40 import net.pterodactylus.util.number.Numbers;
41 import net.pterodactylus.util.service.AbstractService;
42 import net.pterodactylus.util.xml.SimpleXML;
43 import net.pterodactylus.util.xml.XML;
45 import org.w3c.dom.Document;
47 import freenet.client.FetchResult;
48 import freenet.keys.FreenetURI;
49 import freenet.support.api.Bucket;
52 * The Sone downloader is responsible for download Sones as they are updated.
54 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56 public class SoneDownloader extends AbstractService {
59 private static final Logger logger = Logging.getLogger(SoneDownloader.class);
61 /** The maximum protocol version. */
62 private static final int MAX_PROTOCOL_VERSION = 0;
65 private final Core core;
67 /** The Freenet interface. */
68 private final FreenetInterface freenetInterface;
70 /** The sones to update. */
71 private final Set<Sone> sones = new HashSet<Sone>();
74 * Creates a new Sone downloader.
78 * @param freenetInterface
79 * The Freenet interface
81 public SoneDownloader(Core core, FreenetInterface freenetInterface) {
82 super("Sone Downloader", false);
84 this.freenetInterface = freenetInterface;
92 * Adds the given Sone to the set of Sones that will be watched for updates.
97 public void addSone(Sone sone) {
98 if (!sones.add(sone)) {
99 freenetInterface.unregisterUsk(sone);
101 freenetInterface.registerUsk(sone, this);
105 * Removes the given Sone from the downloader.
108 * The Sone to stop watching
110 public void removeSone(Sone sone) {
111 if (sones.remove(sone)) {
112 freenetInterface.unregisterUsk(sone);
117 * Fetches the updated Sone. This method is a callback method for
118 * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
123 public void fetchSone(Sone sone) {
124 fetchSone(sone, sone.getRequestUri().sskForUSK());
128 * Fetches the updated Sone. This method can be used to fetch a Sone from a
134 * The URI to fetch the Sone from
136 public void fetchSone(Sone sone, FreenetURI soneUri) {
137 fetchSone(sone, soneUri, false);
141 * Fetches the Sone from the given URI.
146 * The URI of the Sone to fetch
148 * {@code true} to only fetch and parse the Sone, {@code false}
149 * to {@link Core#updateSone(Sone) update} it in the core
150 * @return The downloaded Sone, or {@code null} if the Sone could not be
153 public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
154 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, soneUri });
155 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
156 core.setSoneStatus(sone, SoneStatus.downloading);
158 Pair<FreenetURI, FetchResult> fetchResults = freenetInterface.fetchUri(requestUri);
159 if (fetchResults == null) {
160 /* TODO - mark Sone as bad. */
163 logger.log(Level.FINEST, "Got %d bytes back.", fetchResults.getRight().size());
164 Sone parsedSone = parseSone(sone, fetchResults.getRight(), fetchResults.getLeft());
165 if (parsedSone != null) {
167 core.updateSone(parsedSone);
173 core.setSoneStatus(sone, (sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
178 * Parses a Sone from a fetch result.
180 * @param originalSone
181 * The sone to parse, or {@code null} if the Sone is yet unknown
186 * @return The parsed Sone, or {@code null} if the Sone could not be parsed
188 public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
189 logger.log(Level.FINEST, "Parsing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), originalSone });
190 Bucket soneBucket = fetchResult.asBucket();
191 InputStream soneInputStream = null;
193 soneInputStream = soneBucket.getInputStream();
194 Sone parsedSone = parseSone(originalSone, soneInputStream);
195 if (parsedSone != null) {
196 parsedSone.setLatestEdition(requestUri.getEdition());
197 if (requestUri.getKeyType().equals("USK")) {
198 parsedSone.setRequestUri(requestUri.setMetaString(new String[0]));
200 parsedSone.setRequestUri(requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]));
204 } catch (Exception e1) {
205 logger.log(Level.WARNING, "Could not parse Sone from " + requestUri + "!", e1);
207 Closer.close(soneInputStream);
214 * Parses a Sone from the given input stream and creates a new Sone from the
217 * @param originalSone
219 * @param soneInputStream
220 * The input stream to parse the Sone from
221 * @return The parsed Sone
223 public Sone parseSone(Sone originalSone, InputStream soneInputStream) {
224 /* TODO - impose a size limit? */
227 /* XML parsing is not thread-safe. */
228 synchronized (this) {
229 document = XML.transformToDocument(soneInputStream);
231 if (document == null) {
232 /* TODO - mark Sone as bad. */
233 logger.log(Level.WARNING, "Could not parse XML for Sone %s!", new Object[] { originalSone });
237 Sone sone = new Sone(originalSone.getId()).setIdentity(originalSone.getIdentity());
241 soneXml = SimpleXML.fromDocument(document);
242 } catch (NullPointerException npe1) {
243 /* for some reason, invalid XML can cause NPEs. */
244 logger.log(Level.WARNING, "XML for Sone " + sone + " can not be parsed!", npe1);
248 Integer protocolVersion = null;
249 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
250 if (soneProtocolVersion != null) {
251 protocolVersion = Numbers.safeParseInteger(soneProtocolVersion);
253 if (protocolVersion == null) {
254 logger.log(Level.INFO, "No protocol version found, assuming 0.");
258 if (protocolVersion < 0) {
259 logger.log(Level.WARNING, "Invalid protocol version: " + protocolVersion + "! Not parsing Sone.");
263 /* check for valid versions. */
264 if (protocolVersion > MAX_PROTOCOL_VERSION) {
265 logger.log(Level.WARNING, "Unknown protocol version: " + protocolVersion + "! Not parsing Sone.");
269 String soneTime = soneXml.getValue("time", null);
270 if (soneTime == null) {
271 /* TODO - mark Sone as bad. */
272 logger.log(Level.WARNING, "Downloaded time for Sone %s was null!", new Object[] { sone });
276 sone.setTime(Long.parseLong(soneTime));
277 } catch (NumberFormatException nfe1) {
278 /* TODO - mark Sone as bad. */
279 logger.log(Level.WARNING, "Downloaded Sone %s with invalid time: %s", new Object[] { sone, soneTime });
283 SimpleXML clientXml = soneXml.getNode("client");
284 if (clientXml != null) {
285 String clientName = clientXml.getValue("name", null);
286 String clientVersion = clientXml.getValue("version", null);
287 if ((clientName == null) || (clientVersion == null)) {
288 logger.log(Level.WARNING, "Download Sone %s with client XML but missing name or version!", sone);
291 sone.setClient(new Client(clientName, clientVersion));
294 String soneRequestUri = soneXml.getValue("request-uri", null);
295 if (soneRequestUri != null) {
297 sone.setRequestUri(new FreenetURI(soneRequestUri));
298 } catch (MalformedURLException mue1) {
299 /* TODO - mark Sone as bad. */
300 logger.log(Level.WARNING, "Downloaded Sone " + sone + " has invalid request URI: " + soneRequestUri, mue1);
305 String soneInsertUri = soneXml.getValue("insert-uri", null);
306 if ((soneInsertUri != null) && (sone.getInsertUri() == null)) {
308 sone.setInsertUri(new FreenetURI(soneInsertUri));
309 sone.setLatestEdition(Math.max(sone.getRequestUri().getEdition(), sone.getInsertUri().getEdition()));
310 } catch (MalformedURLException mue1) {
311 /* TODO - mark Sone as bad. */
312 logger.log(Level.WARNING, "Downloaded Sone " + sone + " has invalid insert URI: " + soneInsertUri, mue1);
317 SimpleXML profileXml = soneXml.getNode("profile");
318 if (profileXml == null) {
319 /* TODO - mark Sone as bad. */
320 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
325 String profileFirstName = profileXml.getValue("first-name", null);
326 String profileMiddleName = profileXml.getValue("middle-name", null);
327 String profileLastName = profileXml.getValue("last-name", null);
328 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
329 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
330 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
331 Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
332 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
334 /* parse profile fields. */
335 SimpleXML profileFieldsXml = profileXml.getNode("fields");
336 if (profileFieldsXml != null) {
337 for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
338 String fieldName = fieldXml.getValue("field-name", null);
339 String fieldValue = fieldXml.getValue("field-value", null);
340 if ((fieldName == null) || (fieldValue == null)) {
341 logger.log(Level.WARNING, "Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", new Object[] { sone, fieldName, fieldValue });
345 profile.addField(fieldName).setValue(fieldValue);
346 } catch (IllegalArgumentException iae1) {
347 logger.log(Level.WARNING, "Duplicate field: " + fieldName, iae1);
354 SimpleXML postsXml = soneXml.getNode("posts");
355 Set<Post> posts = new HashSet<Post>();
356 if (postsXml == null) {
357 /* TODO - mark Sone as bad. */
358 logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
360 for (SimpleXML postXml : postsXml.getNodes("post")) {
361 String postId = postXml.getValue("id", null);
362 String postRecipientId = postXml.getValue("recipient", null);
363 String postTime = postXml.getValue("time", null);
364 String postText = postXml.getValue("text", null);
365 if ((postId == null) || (postTime == null) || (postText == null)) {
366 /* TODO - mark Sone as bad. */
367 logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
371 Post post = core.getPost(postId).setSone(sone).setTime(Long.parseLong(postTime)).setText(postText);
372 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
373 post.setRecipient(core.getSone(postRecipientId));
376 } catch (NumberFormatException nfe1) {
377 /* TODO - mark Sone as bad. */
378 logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
385 SimpleXML repliesXml = soneXml.getNode("replies");
386 Set<Reply> replies = new HashSet<Reply>();
387 if (repliesXml == null) {
388 /* TODO - mark Sone as bad. */
389 logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
391 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
392 String replyId = replyXml.getValue("id", null);
393 String replyPostId = replyXml.getValue("post-id", null);
394 String replyTime = replyXml.getValue("time", null);
395 String replyText = replyXml.getValue("text", null);
396 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
397 /* TODO - mark Sone as bad. */
398 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 });
402 replies.add(core.getReply(replyId).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
403 } catch (NumberFormatException nfe1) {
404 /* TODO - mark Sone as bad. */
405 logger.log(Level.WARNING, "Downloaded reply for Sone %s with invalid time: %s", new Object[] { sone, replyTime });
411 /* parse liked post IDs. */
412 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
413 Set<String> likedPostIds = new HashSet<String>();
414 if (likePostIdsXml == null) {
415 /* TODO - mark Sone as bad. */
416 logger.log(Level.WARNING, "Downloaded Sone %s has no post likes!", new Object[] { sone });
418 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
419 String postId = likedPostIdXml.getValue();
420 likedPostIds.add(postId);
424 /* parse liked reply IDs. */
425 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
426 Set<String> likedReplyIds = new HashSet<String>();
427 if (likeReplyIdsXml == null) {
428 /* TODO - mark Sone as bad. */
429 logger.log(Level.WARNING, "Downloaded Sone %s has no reply likes!", new Object[] { sone });
431 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
432 String replyId = likedReplyIdXml.getValue();
433 likedReplyIds.add(replyId);
438 SimpleXML albumsXml = soneXml.getNode("albums");
439 List<Album> topLevelAlbums = new ArrayList<Album>();
440 if (albumsXml != null) {
441 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
442 String id = albumXml.getValue("id", null);
443 String parentId = albumXml.getValue("parent", null);
444 String title = albumXml.getValue("title", null);
445 String description = albumXml.getValue("description", null);
446 String albumImageId = albumXml.getValue("album-image", null);
447 if ((id == null) || (title == null) || (description == null)) {
448 logger.log(Level.WARNING, "Downloaded Sone %s contains invalid album!", new Object[] { sone });
452 if (parentId != null) {
453 parent = core.getAlbum(parentId, false);
454 if (parent == null) {
455 logger.log(Level.WARNING, "Downloaded Sone %s has album with invalid parent!", new Object[] { sone });
459 Album album = core.getAlbum(id).setSone(sone).setTitle(title).setDescription(description).setAlbumImage(albumImageId);
460 if (parent != null) {
461 parent.addAlbum(album);
463 topLevelAlbums.add(album);
465 SimpleXML imagesXml = albumXml.getNode("images");
466 if (imagesXml != null) {
467 for (SimpleXML imageXml : imagesXml.getNodes("image")) {
468 String imageId = imageXml.getValue("id", null);
469 String imageCreationTimeString = imageXml.getValue("creation-time", null);
470 String imageKey = imageXml.getValue("key", null);
471 String imageTitle = imageXml.getValue("title", null);
472 String imageDescription = imageXml.getValue("description", "");
473 String imageWidthString = imageXml.getValue("width", null);
474 String imageHeightString = imageXml.getValue("height", null);
475 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
476 logger.log(Level.WARNING, "Downloaded Sone %s contains invalid images!", new Object[] { sone });
479 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
480 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
481 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
482 if ((imageWidth < 1) || (imageHeight < 1)) {
483 logger.log(Level.WARNING, "Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", new Object[] { sone, imageId, imageWidthString, imageHeightString });
486 Image image = core.getImage(imageId).setSone(sone).setKey(imageKey).setCreationTime(creationTime);
487 image.setTitle(imageTitle).setDescription(imageDescription);
488 image.setWidth(imageWidth).setHeight(imageHeight);
489 album.addImage(image);
495 /* okay, apparently everything was parsed correctly. Now import. */
496 /* atomic setter operation on the Sone. */
497 synchronized (sone) {
498 sone.setProfile(profile);
499 sone.setPosts(posts);
500 sone.setReplies(replies);
501 sone.setLikePostIds(likedPostIds);
502 sone.setLikeReplyIds(likedReplyIds);
503 sone.setAlbums(topLevelAlbums);
517 protected void serviceStop() {
518 for (Sone sone : sones) {
519 freenetInterface.unregisterUsk(sone);