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