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