Rename post and reply implementations; use builder to create replies.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneDownloader.java
1 /*
2  * Sone - SoneDownloader.java - Copyright © 2010–2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.core;
19
20 import static com.google.common.base.Optional.of;
21
22 import java.io.InputStream;
23 import java.net.MalformedURLException;
24 import java.util.HashSet;
25 import java.util.Map;
26 import java.util.Set;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import net.pterodactylus.sone.core.FreenetInterface.Fetched;
31 import net.pterodactylus.sone.data.Album;
32 import net.pterodactylus.sone.data.Client;
33 import net.pterodactylus.sone.data.Image;
34 import net.pterodactylus.sone.data.Post;
35 import net.pterodactylus.sone.data.PostReply;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Sone;
38 import net.pterodactylus.sone.data.Sone.SoneStatus;
39 import net.pterodactylus.sone.data.impl.DefaultSone;
40 import net.pterodactylus.sone.database.PostBuilder;
41 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
42 import net.pterodactylus.sone.database.PostReplyBuilder;
43 import net.pterodactylus.sone.database.PostReplyBuilder.PostReplyCreated;
44 import net.pterodactylus.util.io.Closer;
45 import net.pterodactylus.util.logging.Logging;
46 import net.pterodactylus.util.number.Numbers;
47 import net.pterodactylus.util.service.AbstractService;
48 import net.pterodactylus.util.xml.SimpleXML;
49 import net.pterodactylus.util.xml.XML;
50
51 import freenet.client.FetchResult;
52 import freenet.keys.FreenetURI;
53 import freenet.support.api.Bucket;
54
55 import com.google.common.base.Optional;
56 import com.google.common.collect.Maps;
57 import org.w3c.dom.Document;
58
59 /**
60  * The Sone downloader is responsible for download Sones as they are updated.
61  *
62  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
63  */
64 public class SoneDownloader extends AbstractService {
65
66         /** The logger. */
67         private static final Logger logger = Logging.getLogger(SoneDownloader.class);
68
69         /** The maximum protocol version. */
70         private static final int MAX_PROTOCOL_VERSION = 0;
71
72         /** The core. */
73         private final Core core;
74
75         /** The Freenet interface. */
76         private final FreenetInterface freenetInterface;
77
78         /** The sones to update. */
79         private final Set<Sone> sones = new HashSet<Sone>();
80
81         /**
82          * Creates a new Sone downloader.
83          *
84          * @param core
85          *            The core
86          * @param freenetInterface
87          *            The Freenet interface
88          */
89         public SoneDownloader(Core core, FreenetInterface freenetInterface) {
90                 super("Sone Downloader", false);
91                 this.core = core;
92                 this.freenetInterface = freenetInterface;
93         }
94
95         //
96         // ACTIONS
97         //
98
99         /**
100          * Adds the given Sone to the set of Sones that will be watched for updates.
101          *
102          * @param sone
103          *            The Sone to add
104          */
105         public void addSone(Sone sone) {
106                 if (!sones.add(sone)) {
107                         freenetInterface.unregisterUsk(sone);
108                 }
109                 freenetInterface.registerUsk(sone, this);
110         }
111
112         /**
113          * Removes the given Sone from the downloader.
114          *
115          * @param sone
116          *            The Sone to stop watching
117          */
118         public void removeSone(Sone sone) {
119                 if (sones.remove(sone)) {
120                         freenetInterface.unregisterUsk(sone);
121                 }
122         }
123
124         /**
125          * Fetches the updated Sone. This method is a callback method for
126          * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
127          *
128          * @param sone
129          *            The Sone to fetch
130          */
131         public void fetchSone(Sone sone) {
132                 fetchSone(sone, sone.getRequestUri().sskForUSK());
133         }
134
135         /**
136          * Fetches the updated Sone. This method can be used to fetch a Sone from a
137          * specific URI.
138          *
139          * @param sone
140          *            The Sone to fetch
141          * @param soneUri
142          *            The URI to fetch the Sone from
143          */
144         public void fetchSone(Sone sone, FreenetURI soneUri) {
145                 fetchSone(sone, soneUri, false);
146         }
147
148         /**
149          * Fetches the Sone from the given URI.
150          *
151          * @param sone
152          *            The Sone to fetch
153          * @param soneUri
154          *            The URI of the Sone to fetch
155          * @param fetchOnly
156          *            {@code true} to only fetch and parse the Sone, {@code false}
157          *            to {@link Core#updateSone(Sone) update} it in the core
158          * @return The downloaded Sone, or {@code null} if the Sone could not be
159          *         downloaded
160          */
161         public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
162                 logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri));
163                 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
164                 sone.setStatus(SoneStatus.downloading);
165                 try {
166                         Fetched fetchResults = freenetInterface.fetchUri(requestUri);
167                         if (fetchResults == null) {
168                                 /* TODO - mark Sone as bad. */
169                                 return null;
170                         }
171                         logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
172                         Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
173                         if (parsedSone != null) {
174                                 if (!fetchOnly) {
175                                         parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
176                                         core.updateSone(parsedSone);
177                                         addSone(parsedSone);
178                                 }
179                         }
180                         return parsedSone;
181                 } finally {
182                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
183                 }
184         }
185
186         /**
187          * Parses a Sone from a fetch result.
188          *
189          * @param originalSone
190          *            The sone to parse, or {@code null} if the Sone is yet unknown
191          * @param fetchResult
192          *            The fetch result
193          * @param requestUri
194          *            The requested URI
195          * @return The parsed Sone, or {@code null} if the Sone could not be parsed
196          */
197         public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
198                 logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone));
199                 Bucket soneBucket = fetchResult.asBucket();
200                 InputStream soneInputStream = null;
201                 try {
202                         soneInputStream = soneBucket.getInputStream();
203                         Sone parsedSone = parseSone(originalSone, soneInputStream);
204                         if (parsedSone != null) {
205                                 parsedSone.setLatestEdition(requestUri.getEdition());
206                                 if (requestUri.getKeyType().equals("USK")) {
207                                         parsedSone.setRequestUri(requestUri.setMetaString(new String[0]));
208                                 } else {
209                                         parsedSone.setRequestUri(requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]));
210                                 }
211                         }
212                         return parsedSone;
213                 } catch (Exception e1) {
214                         logger.log(Level.WARNING, String.format("Could not parse Sone from %s!", requestUri), e1);
215                 } finally {
216                         Closer.close(soneInputStream);
217                         soneBucket.free();
218                 }
219                 return null;
220         }
221
222         /**
223          * Parses a Sone from the given input stream and creates a new Sone from the
224          * parsed data.
225          *
226          * @param originalSone
227          *            The Sone to update
228          * @param soneInputStream
229          *            The input stream to parse the Sone from
230          * @return The parsed Sone
231          * @throws SoneException
232          *             if a parse error occurs, or the protocol is invalid
233          */
234         public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
235                 /* TODO - impose a size limit? */
236
237                 Document document;
238                 /* XML parsing is not thread-safe. */
239                 synchronized (this) {
240                         document = XML.transformToDocument(soneInputStream);
241                 }
242                 if (document == null) {
243                         /* TODO - mark Sone as bad. */
244                         logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
245                         return null;
246                 }
247
248                 Sone sone = new DefaultSone(core.getDatabase(), originalSone.getId(), originalSone.isLocal()).setIdentity(originalSone.getIdentity());
249
250                 SimpleXML soneXml;
251                 try {
252                         soneXml = SimpleXML.fromDocument(document);
253                 } catch (NullPointerException npe1) {
254                         /* for some reason, invalid XML can cause NPEs. */
255                         logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1);
256                         return null;
257                 }
258
259                 Integer protocolVersion = null;
260                 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
261                 if (soneProtocolVersion != null) {
262                         protocolVersion = Numbers.safeParseInteger(soneProtocolVersion);
263                 }
264                 if (protocolVersion == null) {
265                         logger.log(Level.INFO, "No protocol version found, assuming 0.");
266                         protocolVersion = 0;
267                 }
268
269                 if (protocolVersion < 0) {
270                         logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
271                         return null;
272                 }
273
274                 /* check for valid versions. */
275                 if (protocolVersion > MAX_PROTOCOL_VERSION) {
276                         logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
277                         return null;
278                 }
279
280                 String soneTime = soneXml.getValue("time", null);
281                 if (soneTime == null) {
282                         /* TODO - mark Sone as bad. */
283                         logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
284                         return null;
285                 }
286                 try {
287                         sone.setTime(Long.parseLong(soneTime));
288                 } catch (NumberFormatException nfe1) {
289                         /* TODO - mark Sone as bad. */
290                         logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
291                         return null;
292                 }
293
294                 SimpleXML clientXml = soneXml.getNode("client");
295                 if (clientXml != null) {
296                         String clientName = clientXml.getValue("name", null);
297                         String clientVersion = clientXml.getValue("version", null);
298                         if ((clientName == null) || (clientVersion == null)) {
299                                 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
300                                 return null;
301                         }
302                         sone.setClient(new Client(clientName, clientVersion));
303                 }
304
305                 String soneRequestUri = soneXml.getValue("request-uri", null);
306                 if (soneRequestUri != null) {
307                         try {
308                                 sone.setRequestUri(new FreenetURI(soneRequestUri));
309                         } catch (MalformedURLException mue1) {
310                                 /* TODO - mark Sone as bad. */
311                                 logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid request URI: %s", sone, soneRequestUri), mue1);
312                                 return null;
313                         }
314                 }
315
316                 if (originalSone.getInsertUri() != null) {
317                         sone.setInsertUri(originalSone.getInsertUri());
318                 }
319
320                 SimpleXML profileXml = soneXml.getNode("profile");
321                 if (profileXml == null) {
322                         /* TODO - mark Sone as bad. */
323                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
324                         return null;
325                 }
326
327                 /* parse profile. */
328                 String profileFirstName = profileXml.getValue("first-name", null);
329                 String profileMiddleName = profileXml.getValue("middle-name", null);
330                 String profileLastName = profileXml.getValue("last-name", null);
331                 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
332                 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
333                 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
334                 Profile profile = new Profile(sone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
335                 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
336                 /* avatar is processed after images are loaded. */
337                 String avatarId = profileXml.getValue("avatar", null);
338
339                 /* parse profile fields. */
340                 SimpleXML profileFieldsXml = profileXml.getNode("fields");
341                 if (profileFieldsXml != null) {
342                         for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
343                                 String fieldName = fieldXml.getValue("field-name", null);
344                                 String fieldValue = fieldXml.getValue("field-value", "");
345                                 if (fieldName == null) {
346                                         logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
347                                         return null;
348                                 }
349                                 try {
350                                         profile.addField(fieldName).setValue(fieldValue);
351                                 } catch (IllegalArgumentException iae1) {
352                                         logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
353                                         return null;
354                                 }
355                         }
356                 }
357
358                 /* parse posts. */
359                 SimpleXML postsXml = soneXml.getNode("posts");
360                 Set<Post> posts = new HashSet<Post>();
361                 if (postsXml == null) {
362                         /* TODO - mark Sone as bad. */
363                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
364                 } else {
365                         for (SimpleXML postXml : postsXml.getNodes("post")) {
366                                 String postId = postXml.getValue("id", null);
367                                 String postRecipientId = postXml.getValue("recipient", null);
368                                 String postTime = postXml.getValue("time", null);
369                                 String postText = postXml.getValue("text", null);
370                                 if ((postId == null) || (postTime == null) || (postText == null)) {
371                                         /* TODO - mark Sone as bad. */
372                                         logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
373                                         return null;
374                                 }
375                                 try {
376                                         PostBuilder postBuilder = sone.newPostBuilder();
377                                         /* TODO - parse time correctly. */
378                                         postBuilder.withId(postId).withTime(Long.parseLong(postTime)).withText(postText);
379                                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
380                                                 postBuilder.to(of(postRecipientId));
381                                         }
382                                         posts.add(postBuilder.build(Optional.<PostCreated>absent()));
383                                 } catch (NumberFormatException nfe1) {
384                                         /* TODO - mark Sone as bad. */
385                                         logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
386                                         return null;
387                                 }
388                         }
389                 }
390
391                 /* parse replies. */
392                 SimpleXML repliesXml = soneXml.getNode("replies");
393                 Set<PostReply> replies = new HashSet<PostReply>();
394                 if (repliesXml == null) {
395                         /* TODO - mark Sone as bad. */
396                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
397                 } else {
398                         for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
399                                 String replyId = replyXml.getValue("id", null);
400                                 String replyPostId = replyXml.getValue("post-id", null);
401                                 String replyTime = replyXml.getValue("time", null);
402                                 String replyText = replyXml.getValue("text", null);
403                                 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
404                                         /* TODO - mark Sone as bad. */
405                                         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));
406                                         return null;
407                                 }
408                                 try {
409                                         /* TODO - parse time correctly. */
410                                         PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(replyPostId).withId(replyId).withTime(Long.parseLong(replyTime)).withText(replyText);
411                                         replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
412                                 } catch (NumberFormatException nfe1) {
413                                         /* TODO - mark Sone as bad. */
414                                         logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
415                                         return null;
416                                 }
417                         }
418                 }
419
420                 /* parse liked post IDs. */
421                 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
422                 Set<String> likedPostIds = new HashSet<String>();
423                 if (likePostIdsXml == null) {
424                         /* TODO - mark Sone as bad. */
425                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
426                 } else {
427                         for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
428                                 String postId = likedPostIdXml.getValue();
429                                 likedPostIds.add(postId);
430                         }
431                 }
432
433                 /* parse liked reply IDs. */
434                 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
435                 Set<String> likedReplyIds = new HashSet<String>();
436                 if (likeReplyIdsXml == null) {
437                         /* TODO - mark Sone as bad. */
438                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
439                 } else {
440                         for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
441                                 String replyId = likedReplyIdXml.getValue();
442                                 likedReplyIds.add(replyId);
443                         }
444                 }
445
446                 /* parse albums. */
447                 SimpleXML albumsXml = soneXml.getNode("albums");
448                 Map<String, Album> albums = Maps.newHashMap();
449                 if (albumsXml != null) {
450                         for (SimpleXML albumXml : albumsXml.getNodes("album")) {
451                                 String id = albumXml.getValue("id", null);
452                                 String parentId = albumXml.getValue("parent", null);
453                                 String title = albumXml.getValue("title", null);
454                                 String description = albumXml.getValue("description", "");
455                                 String albumImageId = albumXml.getValue("album-image", null);
456                                 if ((id == null) || (title == null) || (description == null)) {
457                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
458                                         return null;
459                                 }
460                                 Album parent = sone.getRootAlbum();
461                                 if (parentId != null) {
462                                         parent = albums.get(parentId);
463                                         if (parent == null) {
464                                                 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
465                                                 return null;
466                                         }
467                                 }
468                                 Album album = parent.newAlbumBuilder().withId(id).build().modify().setTitle(title).setDescription(description).update();
469                                 albums.put(album.getId(), album);
470                                 SimpleXML imagesXml = albumXml.getNode("images");
471                                 if (imagesXml != null) {
472                                         for (SimpleXML imageXml : imagesXml.getNodes("image")) {
473                                                 String imageId = imageXml.getValue("id", null);
474                                                 String imageCreationTimeString = imageXml.getValue("creation-time", null);
475                                                 String imageKey = imageXml.getValue("key", null);
476                                                 String imageTitle = imageXml.getValue("title", null);
477                                                 String imageDescription = imageXml.getValue("description", "");
478                                                 String imageWidthString = imageXml.getValue("width", null);
479                                                 String imageHeightString = imageXml.getValue("height", null);
480                                                 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
481                                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
482                                                         return null;
483                                                 }
484                                                 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
485                                                 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
486                                                 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
487                                                 if ((imageWidth < 1) || (imageHeight < 1)) {
488                                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
489                                                         return null;
490                                                 }
491                                                 Image image = album.newImageBuilder().withId(imageId).at(imageKey).created(creationTime).sized(imageWidth, imageHeight).build();
492                                                 image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
493                                         }
494                                 }
495                                 album.modify().setAlbumImage(albumImageId).update();
496                         }
497                 }
498
499                 /* process avatar. */
500                 if (avatarId != null) {
501                         profile.setAvatar(core.getImage(avatarId).orNull());
502                 }
503
504                 /* okay, apparently everything was parsed correctly. Now import. */
505                 /* atomic setter operation on the Sone. */
506                 synchronized (sone) {
507                         sone.setProfile(profile);
508                         sone.setPosts(posts);
509                         sone.setReplies(replies);
510                         sone.setLikePostIds(likedPostIds);
511                         sone.setLikeReplyIds(likedReplyIds);
512                 }
513
514                 return sone;
515         }
516
517         //
518         // SERVICE METHODS
519         //
520
521         /**
522          * {@inheritDoc}
523          */
524         @Override
525         protected void serviceStop() {
526                 for (Sone sone : sones) {
527                         freenetInterface.unregisterUsk(sone);
528                 }
529         }
530
531 }