Merge commit 'da609f721e54691f27113e877a19637bd332abc3' into less-critical
[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 java.io.InputStream;
21 import java.net.MalformedURLException;
22 import java.util.ArrayList;
23 import java.util.HashSet;
24 import java.util.List;
25 import java.util.Set;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sone.core.FreenetInterface.Fetched;
30 import net.pterodactylus.sone.data.Album;
31 import net.pterodactylus.sone.data.Client;
32 import net.pterodactylus.sone.data.Image;
33 import net.pterodactylus.sone.data.Post;
34 import net.pterodactylus.sone.data.PostBuilder;
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.util.io.Closer;
40 import net.pterodactylus.util.logging.Logging;
41 import net.pterodactylus.util.number.Numbers;
42 import net.pterodactylus.util.service.AbstractService;
43 import net.pterodactylus.util.xml.SimpleXML;
44 import net.pterodactylus.util.xml.XML;
45
46 import org.w3c.dom.Document;
47
48 import freenet.client.FetchResult;
49 import freenet.keys.FreenetURI;
50 import freenet.support.api.Bucket;
51
52 /**
53  * The Sone downloader is responsible for download Sones as they are updated.
54  *
55  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56  */
57 public class SoneDownloader extends AbstractService {
58
59         /** The logger. */
60         private static final Logger logger = Logging.getLogger(SoneDownloader.class);
61
62         /** The maximum protocol version. */
63         private static final int MAX_PROTOCOL_VERSION = 0;
64
65         /** The core. */
66         private final Core core;
67
68         /** The Freenet interface. */
69         private final FreenetInterface freenetInterface;
70
71         /** The sones to update. */
72         private final Set<Sone> sones = new HashSet<Sone>();
73
74         /**
75          * Creates a new Sone downloader.
76          *
77          * @param core
78          *            The core
79          * @param freenetInterface
80          *            The Freenet interface
81          */
82         public SoneDownloader(Core core, FreenetInterface freenetInterface) {
83                 super("Sone Downloader", false);
84                 this.core = core;
85                 this.freenetInterface = freenetInterface;
86         }
87
88         //
89         // ACTIONS
90         //
91
92         /**
93          * Adds the given Sone to the set of Sones that will be watched for updates.
94          *
95          * @param sone
96          *            The Sone to add
97          */
98         public void addSone(Sone sone) {
99                 if (!sones.add(sone)) {
100                         freenetInterface.unregisterUsk(sone);
101                 }
102                 freenetInterface.registerUsk(sone, this);
103         }
104
105         /**
106          * Removes the given Sone from the downloader.
107          *
108          * @param sone
109          *            The Sone to stop watching
110          */
111         public void removeSone(Sone sone) {
112                 if (sones.remove(sone)) {
113                         freenetInterface.unregisterUsk(sone);
114                 }
115         }
116
117         /**
118          * Fetches the updated Sone. This method is a callback method for
119          * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
120          *
121          * @param sone
122          *            The Sone to fetch
123          */
124         public void fetchSone(Sone sone) {
125                 fetchSone(sone, sone.getRequestUri().sskForUSK());
126         }
127
128         /**
129          * Fetches the updated Sone. This method can be used to fetch a Sone from a
130          * specific URI.
131          *
132          * @param sone
133          *            The Sone to fetch
134          * @param soneUri
135          *            The URI to fetch the Sone from
136          */
137         public void fetchSone(Sone sone, FreenetURI soneUri) {
138                 fetchSone(sone, soneUri, false);
139         }
140
141         /**
142          * Fetches the Sone from the given URI.
143          *
144          * @param sone
145          *            The Sone to fetch
146          * @param soneUri
147          *            The URI of the Sone to fetch
148          * @param fetchOnly
149          *            {@code true} to only fetch and parse the Sone, {@code false}
150          *            to {@link Core#updateSone(Sone) update} it in the core
151          * @return The downloaded Sone, or {@code null} if the Sone could not be
152          *         downloaded
153          */
154         public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
155                 logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri));
156                 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
157                 sone.setStatus(SoneStatus.downloading);
158                 try {
159                         Fetched fetchResults = freenetInterface.fetchUri(requestUri);
160                         if (fetchResults == null) {
161                                 /* TODO - mark Sone as bad. */
162                                 return null;
163                         }
164                         logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
165                         Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
166                         if (parsedSone != null) {
167                                 if (!fetchOnly) {
168                                         core.updateSone(parsedSone);
169                                         addSone(parsedSone);
170                                 }
171                         }
172                         return parsedSone;
173                 } finally {
174                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
175                 }
176         }
177
178         /**
179          * Parses a Sone from a fetch result.
180          *
181          * @param originalSone
182          *            The sone to parse, or {@code null} if the Sone is yet unknown
183          * @param fetchResult
184          *            The fetch result
185          * @param requestUri
186          *            The requested URI
187          * @return The parsed Sone, or {@code null} if the Sone could not be parsed
188          */
189         public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
190                 logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone));
191                 Bucket soneBucket = fetchResult.asBucket();
192                 InputStream soneInputStream = null;
193                 try {
194                         soneInputStream = soneBucket.getInputStream();
195                         Sone parsedSone = parseSone(originalSone, soneInputStream);
196                         if (parsedSone != null) {
197                                 parsedSone.setLatestEdition(requestUri.getEdition());
198                                 if (requestUri.getKeyType().equals("USK")) {
199                                         parsedSone.setRequestUri(requestUri.setMetaString(new String[0]));
200                                 } else {
201                                         parsedSone.setRequestUri(requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]));
202                                 }
203                         }
204                         return parsedSone;
205                 } catch (Exception e1) {
206                         logger.log(Level.WARNING, String.format("Could not parse Sone from %s!", requestUri), e1);
207                 } finally {
208                         Closer.close(soneInputStream);
209                         soneBucket.free();
210                 }
211                 return null;
212         }
213
214         /**
215          * Parses a Sone from the given input stream and creates a new Sone from the
216          * parsed data.
217          *
218          * @param originalSone
219          *            The Sone to update
220          * @param soneInputStream
221          *            The input stream to parse the Sone from
222          * @return The parsed Sone
223          * @throws SoneException
224          *             if a parse error occurs, or the protocol is invalid
225          */
226         public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
227                 /* TODO - impose a size limit? */
228
229                 Document document;
230                 /* XML parsing is not thread-safe. */
231                 synchronized (this) {
232                         document = XML.transformToDocument(soneInputStream);
233                 }
234                 if (document == null) {
235                         /* TODO - mark Sone as bad. */
236                         logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
237                         return null;
238                 }
239
240                 Sone sone = new Sone(originalSone.getId(), false).setIdentity(originalSone.getIdentity());
241
242                 SimpleXML soneXml;
243                 try {
244                         soneXml = SimpleXML.fromDocument(document);
245                 } catch (NullPointerException npe1) {
246                         /* for some reason, invalid XML can cause NPEs. */
247                         logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1);
248                         return null;
249                 }
250
251                 Integer protocolVersion = null;
252                 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
253                 if (soneProtocolVersion != null) {
254                         protocolVersion = Numbers.safeParseInteger(soneProtocolVersion);
255                 }
256                 if (protocolVersion == null) {
257                         logger.log(Level.INFO, "No protocol version found, assuming 0.");
258                         protocolVersion = 0;
259                 }
260
261                 if (protocolVersion < 0) {
262                         logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
263                         return null;
264                 }
265
266                 /* check for valid versions. */
267                 if (protocolVersion > MAX_PROTOCOL_VERSION) {
268                         logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
269                         return null;
270                 }
271
272                 String soneTime = soneXml.getValue("time", null);
273                 if (soneTime == null) {
274                         /* TODO - mark Sone as bad. */
275                         logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
276                         return null;
277                 }
278                 try {
279                         sone.setTime(Long.parseLong(soneTime));
280                 } catch (NumberFormatException nfe1) {
281                         /* TODO - mark Sone as bad. */
282                         logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
283                         return null;
284                 }
285
286                 SimpleXML clientXml = soneXml.getNode("client");
287                 if (clientXml != null) {
288                         String clientName = clientXml.getValue("name", null);
289                         String clientVersion = clientXml.getValue("version", null);
290                         if ((clientName == null) || (clientVersion == null)) {
291                                 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
292                                 return null;
293                         }
294                         sone.setClient(new Client(clientName, clientVersion));
295                 }
296
297                 String soneRequestUri = soneXml.getValue("request-uri", null);
298                 if (soneRequestUri != null) {
299                         try {
300                                 sone.setRequestUri(new FreenetURI(soneRequestUri));
301                         } catch (MalformedURLException mue1) {
302                                 /* TODO - mark Sone as bad. */
303                                 logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid request URI: %s", sone, soneRequestUri), mue1);
304                                 return null;
305                         }
306                 }
307
308                 String soneInsertUri = soneXml.getValue("insert-uri", null);
309                 if ((soneInsertUri != null) && (sone.getInsertUri() == null)) {
310                         try {
311                                 sone.setInsertUri(new FreenetURI(soneInsertUri));
312                                 sone.setLatestEdition(Math.max(sone.getRequestUri().getEdition(), sone.getInsertUri().getEdition()));
313                         } catch (MalformedURLException mue1) {
314                                 /* TODO - mark Sone as bad. */
315                                 logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid insert URI: %s", sone, soneInsertUri), mue1);
316                                 return null;
317                         }
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 = core.postBuilder();
377                                         /* TODO - parse time correctly. */
378                                         postBuilder.withId(postId).from(sone).withTime(Long.parseLong(postTime)).withText(postText);
379                                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
380                                                 postBuilder.to(core.getSone(postRecipientId));
381                                         }
382                                         posts.add(postBuilder.build());
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                                         replies.add(core.getPostReply(replyId, true).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
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                 List<Album> topLevelAlbums = new ArrayList<Album>();
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 = null;
459                                 if (parentId != null) {
460                                         parent = core.getAlbum(parentId, false);
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 = core.getAlbum(id).setSone(sone).setTitle(title).setDescription(description);
467                                 if (parent != null) {
468                                         parent.addAlbum(album);
469                                 } else {
470                                         topLevelAlbums.add(album);
471                                 }
472                                 SimpleXML imagesXml = albumXml.getNode("images");
473                                 if (imagesXml != null) {
474                                         for (SimpleXML imageXml : imagesXml.getNodes("image")) {
475                                                 String imageId = imageXml.getValue("id", null);
476                                                 String imageCreationTimeString = imageXml.getValue("creation-time", null);
477                                                 String imageKey = imageXml.getValue("key", null);
478                                                 String imageTitle = imageXml.getValue("title", null);
479                                                 String imageDescription = imageXml.getValue("description", "");
480                                                 String imageWidthString = imageXml.getValue("width", null);
481                                                 String imageHeightString = imageXml.getValue("height", null);
482                                                 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
483                                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
484                                                         return null;
485                                                 }
486                                                 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
487                                                 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
488                                                 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
489                                                 if ((imageWidth < 1) || (imageHeight < 1)) {
490                                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
491                                                         return null;
492                                                 }
493                                                 Image image = core.getImage(imageId).setSone(sone).setKey(imageKey).setCreationTime(creationTime);
494                                                 image.setTitle(imageTitle).setDescription(imageDescription);
495                                                 image.setWidth(imageWidth).setHeight(imageHeight);
496                                                 album.addImage(image);
497                                         }
498                                 }
499                                 album.setAlbumImage(albumImageId);
500                         }
501                 }
502
503                 /* process avatar. */
504                 if (avatarId != null) {
505                         profile.setAvatar(core.getImage(avatarId, false));
506                 }
507
508                 /* okay, apparently everything was parsed correctly. Now import. */
509                 /* atomic setter operation on the Sone. */
510                 synchronized (sone) {
511                         sone.setProfile(profile);
512                         sone.setPosts(posts);
513                         sone.setReplies(replies);
514                         sone.setLikePostIds(likedPostIds);
515                         sone.setLikeReplyIds(likedReplyIds);
516                         sone.setAlbums(topLevelAlbums);
517                 }
518
519                 return sone;
520         }
521
522         //
523         // SERVICE METHODS
524         //
525
526         /**
527          * {@inheritDoc}
528          */
529         @Override
530         protected void serviceStop() {
531                 for (Sone sone : sones) {
532                         freenetInterface.unregisterUsk(sone);
533                 }
534         }
535
536 }