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