Refactoring to allow several entry points for parseSone().
[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.HashSet;
24 import java.util.Set;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27
28 import net.pterodactylus.sone.core.Core.SoneStatus;
29 import net.pterodactylus.sone.data.Post;
30 import net.pterodactylus.sone.data.Profile;
31 import net.pterodactylus.sone.data.Reply;
32 import net.pterodactylus.sone.data.Sone;
33 import net.pterodactylus.util.io.Closer;
34 import net.pterodactylus.util.logging.Logging;
35 import net.pterodactylus.util.number.Numbers;
36 import net.pterodactylus.util.service.AbstractService;
37 import net.pterodactylus.util.xml.SimpleXML;
38 import net.pterodactylus.util.xml.XML;
39
40 import org.w3c.dom.Document;
41
42 import freenet.client.FetchResult;
43 import freenet.keys.FreenetURI;
44 import freenet.support.api.Bucket;
45
46 /**
47  * The Sone downloader is responsible for download Sones as they are updated.
48  *
49  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50  */
51 public class SoneDownloader extends AbstractService {
52
53         /** The logger. */
54         private static final Logger logger = Logging.getLogger(SoneDownloader.class);
55
56         /** The core. */
57         private final Core core;
58
59         /** The Freenet interface. */
60         private final FreenetInterface freenetInterface;
61
62         /** The sones to update. */
63         private final Set<Sone> sones = new HashSet<Sone>();
64
65         /**
66          * Creates a new Sone downloader.
67          *
68          * @param core
69          *            The core
70          * @param freenetInterface
71          *            The Freenet interface
72          */
73         public SoneDownloader(Core core, FreenetInterface freenetInterface) {
74                 super("Sone Downloader", false);
75                 this.core = core;
76                 this.freenetInterface = freenetInterface;
77         }
78
79         //
80         // ACTIONS
81         //
82
83         /**
84          * Adds the given Sone to the set of Sones that will be watched for updates.
85          *
86          * @param sone
87          *            The Sone to add
88          */
89         public void addSone(Sone sone) {
90                 if (sones.add(sone)) {
91                         freenetInterface.registerUsk(sone, this);
92                 }
93         }
94
95         /**
96          * Removes the given Sone from the downloader.
97          *
98          * @param sone
99          *            The Sone to stop watching
100          */
101         public void removeSone(Sone sone) {
102                 if (sones.remove(sone)) {
103                         freenetInterface.unregisterUsk(sone);
104                 }
105         }
106
107         /**
108          * Fetches the updated Sone. This method is a callback method for
109          * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
110          *
111          * @param sone
112          *            The Sone to fetch
113          */
114         public void fetchSone(Sone sone) {
115                 if (core.getSoneStatus(sone) == SoneStatus.downloading) {
116                         return;
117                 }
118                 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
119                 FreenetURI requestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
120                 core.setSoneStatus(sone, SoneStatus.downloading);
121                 try {
122                         FetchResult fetchResult = freenetInterface.fetchUri(requestUri);
123                         if (fetchResult == null) {
124                                 /* TODO - mark Sone as bad. */
125                                 return;
126                         }
127                         logger.log(Level.FINEST, "Got %d bytes back.", fetchResult.size());
128                         Sone parsedSone = parseSone(sone, fetchResult, requestUri);
129                         if (parsedSone != null) {
130                                 core.addSone(parsedSone);
131                         }
132                 } finally {
133                         core.setSoneStatus(sone, (sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
134                 }
135         }
136
137         /**
138          * Parses a Sone from a fetch result.
139          *
140          * @param originalSone
141          *            The sone to parse, or {@code null} if the Sone is yet unknown
142          * @param fetchResult
143          *            The fetch result
144          * @param requestUri
145          *            The requested URI
146          * @return The parsed Sone, or {@code null} if the Sone could not be parsed
147          */
148         public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
149                 logger.log(Level.FINEST, "Persing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), originalSone });
150                 Bucket soneBucket = fetchResult.asBucket();
151                 InputStream soneInputStream = null;
152                 try {
153                         soneInputStream = soneBucket.getInputStream();
154                         Sone parsedSone = parseSone(originalSone, soneInputStream);
155                         if (parsedSone != null) {
156                                 parsedSone.setRequestUri(requestUri.setMetaString(new String[0]));
157                         }
158                         return parsedSone;
159                 } catch (IOException ioe1) {
160                         logger.log(Level.WARNING, "Could not parse Sone from " + requestUri + "!", ioe1);
161                 } finally {
162                         Closer.close(soneInputStream);
163                         soneBucket.free();
164                 }
165                 return null;
166         }
167
168         /**
169          * Parses a Sone from the given input stream.
170          *
171          * @param soneInputStream
172          *            The input stream to parse the Sone from
173          * @return The parsed Sone
174          */
175         public Sone parseSone(InputStream soneInputStream) {
176                 return parseSone(null, soneInputStream);
177         }
178
179         /**
180          * Parses a Sone from the given input stream and updates the given Sone, or
181          * creates a new Sone.
182          *
183          * @param originalSone
184          *            The Sone to update (may be {@code null})
185          * @param soneInputStream
186          *            The input stream to parse the Sone from
187          * @return The parsed Sone
188          */
189         public Sone parseSone(Sone originalSone, InputStream soneInputStream) {
190                 /* TODO - impose a size limit? */
191                 Sone sone;
192
193                 Document document;
194                 /* XML parsing is not thread-safe. */
195                 synchronized (this) {
196                         document = XML.transformToDocument(soneInputStream);
197                 }
198                 if (document == null) {
199                         /* TODO - mark Sone as bad. */
200                         logger.log(Level.WARNING, "Could not parse XML for Sone %s!", new Object[] { originalSone });
201                         return null;
202                 }
203                 SimpleXML soneXml;
204                 try {
205                         soneXml = SimpleXML.fromDocument(document);
206                 } catch (NullPointerException npe1) {
207                         /* for some reason, invalid XML can cause NPEs. */
208                         logger.log(Level.WARNING, "XML for Sone " + originalSone + " can not be parsed!", npe1);
209                         return null;
210                 }
211
212                 /* check ID. */
213                 String soneId = soneXml.getValue("id", null);
214                 if ((originalSone != null) && !originalSone.getId().equals(soneId)) {
215                         /* TODO - mark Sone as bad. */
216                         logger.log(Level.WARNING, "Downloaded ID for Sone %s (%s) does not match known ID (%s)!", new Object[] { originalSone, originalSone.getId(), soneId });
217                         return null;
218                 }
219
220                 /* load Sone from core. */
221                 sone = originalSone;
222                 if (sone == null) {
223                         sone = core.getSone(soneId);
224                 }
225
226                 String soneName = soneXml.getValue("name", null);
227                 if (soneName == null) {
228                         /* TODO - mark Sone as bad. */
229                         logger.log(Level.WARNING, "Downloaded name for Sone %s was null!", new Object[] { sone });
230                         return null;
231                 }
232                 sone.setName(soneName);
233
234                 String soneTime = soneXml.getValue("time", null);
235                 if (soneTime == null) {
236                         /* TODO - mark Sone as bad. */
237                         logger.log(Level.WARNING, "Downloaded time for Sone %s was null!", new Object[] { sone });
238                         return null;
239                 }
240                 try {
241                         sone.setTime(Long.parseLong(soneTime));
242                 } catch (NumberFormatException nfe1) {
243                         /* TODO - mark Sone as bad. */
244                         logger.log(Level.WARNING, "Downloaded Sone %s with invalid time: %s", new Object[] { sone, soneTime });
245                         return null;
246                 }
247
248                 String soneRequestUri = soneXml.getValue("request-uri", null);
249                 if (soneRequestUri != null) {
250                         try {
251                                 sone.setRequestUri(new FreenetURI(soneRequestUri));
252                         } catch (MalformedURLException mue1) {
253                                 /* TODO - mark Sone as bad. */
254                                 logger.log(Level.WARNING, "Downloaded Sone " + sone + " has invalid request URI: " + soneRequestUri, mue1);
255                                 return null;
256                         }
257                 }
258
259                 String soneInsertUri = soneXml.getValue("insert-uri", null);
260                 if (soneInsertUri != null) {
261                         try {
262                                 sone.setInsertUri(new FreenetURI(soneInsertUri));
263                         } catch (MalformedURLException mue1) {
264                                 /* TODO - mark Sone as bad. */
265                                 logger.log(Level.WARNING, "Downloaded Sone " + sone + " has invalid insert URI: " + soneInsertUri, mue1);
266                                 return null;
267                         }
268                 }
269
270                 SimpleXML profileXml = soneXml.getNode("profile");
271                 if (profileXml == null) {
272                         /* TODO - mark Sone as bad. */
273                         logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
274                         return null;
275                 }
276
277                 /* parse profile. */
278                 String profileFirstName = profileXml.getValue("first-name", null);
279                 String profileMiddleName = profileXml.getValue("middle-name", null);
280                 String profileLastName = profileXml.getValue("last-name", null);
281                 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
282                 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
283                 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
284                 Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
285                 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
286
287                 /* parse posts. */
288                 SimpleXML postsXml = soneXml.getNode("posts");
289                 Set<Post> posts = new HashSet<Post>();
290                 if (postsXml == null) {
291                         /* TODO - mark Sone as bad. */
292                         logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
293                 } else {
294                         for (SimpleXML postXml : postsXml.getNodes("post")) {
295                                 String postId = postXml.getValue("id", null);
296                                 String postTime = postXml.getValue("time", null);
297                                 String postText = postXml.getValue("text", null);
298                                 if ((postId == null) || (postTime == null) || (postText == null)) {
299                                         /* TODO - mark Sone as bad. */
300                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
301                                         return null;
302                                 }
303                                 try {
304                                         posts.add(core.getPost(postId).setSone(sone).setTime(Long.parseLong(postTime)).setText(postText));
305                                 } catch (NumberFormatException nfe1) {
306                                         /* TODO - mark Sone as bad. */
307                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
308                                         return null;
309                                 }
310                         }
311                 }
312
313                 /* parse replies. */
314                 SimpleXML repliesXml = soneXml.getNode("replies");
315                 Set<Reply> replies = new HashSet<Reply>();
316                 if (repliesXml == null) {
317                         /* TODO - mark Sone as bad. */
318                         logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
319                 } else {
320                         for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
321                                 String replyId = replyXml.getValue("id", null);
322                                 String replyPostId = replyXml.getValue("post-id", null);
323                                 String replyTime = replyXml.getValue("time", null);
324                                 String replyText = replyXml.getValue("text", null);
325                                 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
326                                         /* TODO - mark Sone as bad. */
327                                         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 });
328                                         return null;
329                                 }
330                                 try {
331                                         replies.add(core.getReply(replyId).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
332                                 } catch (NumberFormatException nfe1) {
333                                         /* TODO - mark Sone as bad. */
334                                         logger.log(Level.WARNING, "Downloaded reply for Sone %s with invalid time: %s", new Object[] { sone, replyTime });
335                                         return null;
336                                 }
337                         }
338                 }
339
340                 /* parse liked post IDs. */
341                 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
342                 Set<String> likedPostIds = new HashSet<String>();
343                 if (likePostIdsXml == null) {
344                         /* TODO - mark Sone as bad. */
345                         logger.log(Level.WARNING, "Downloaded Sone %s has no post likes!", new Object[] { sone });
346                 } else {
347                         for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
348                                 String postId = likedPostIdXml.getValue();
349                                 likedPostIds.add(postId);
350                         }
351                 }
352
353                 /* parse liked reply IDs. */
354                 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
355                 Set<String> likedReplyIds = new HashSet<String>();
356                 if (likeReplyIdsXml == null) {
357                         /* TODO - mark Sone as bad. */
358                         logger.log(Level.WARNING, "Downloaded Sone %s has no reply likes!", new Object[] { sone });
359                 } else {
360                         for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
361                                 String replyId = likedReplyIdXml.getValue();
362                                 likedReplyIds.add(replyId);
363                         }
364                 }
365
366                 /* parse known Sones. */
367                 SimpleXML knownSonesXml = soneXml.getNode("known-sones");
368                 Set<Sone> knownSones = new HashSet<Sone>();
369                 if (knownSonesXml == null) {
370                         /* TODO - mark Sone as bad. */
371                         logger.log(Level.WARNING, "Downloaded Sone %s has no known Sones!", new Object[] { sone });
372                 } else {
373                         for (SimpleXML knownSoneXml : knownSonesXml.getNodes("known-sone")) {
374                                 String knownSoneId = knownSoneXml.getValue("sone-id", null);
375                                 String knownSoneKey = knownSoneXml.getValue("sone-key", null);
376                                 String knownSoneName = knownSoneXml.getValue("sone-name", null);
377                                 if ((knownSoneId == null) || (knownSoneKey == null) || (knownSoneName == null)) {
378                                         /* TODO - mark Sone as bad. */
379                                         logger.log(Level.WARNING, "Downloaded known Sone for Sone %s with missing data! ID: %s, Key: %s, Name: %s", new Object[] { sone, knownSoneId, knownSoneKey, knownSoneName });
380                                         return null;
381                                 }
382                                 try {
383                                         knownSones.add(core.getSone(knownSoneId).setRequestUri(new FreenetURI(knownSoneKey)).setName(knownSoneName));
384                                 } catch (MalformedURLException mue1) {
385                                         /* TODO - mark Sone as bad. */
386                                         logger.log(Level.WARNING, "Downloaded known Sone for Sone %s with invalid key: %s", new Object[] { sone, knownSoneKey });
387                                         return null;
388                                 }
389                         }
390                 }
391
392                 /* okay, apparently everything was parsed correctly. Now import. */
393                 /* atomic setter operation on the Sone. */
394                 synchronized (sone) {
395                         sone.setProfile(profile);
396                         sone.setPosts(posts);
397                         sone.setReplies(replies);
398                         sone.setLikePostIds(likedPostIds);
399                         sone.setModificationCounter(0);
400                 }
401
402                 /* add all known Sones to core for downloading. */
403                 for (Sone knownSone : knownSones) {
404                         core.addSone(knownSone);
405                 }
406                 return sone;
407         }
408
409         //
410         // SERVICE METHODS
411         //
412
413         /**
414          * {@inheritDoc}
415          */
416         @Override
417         protected void serviceStop() {
418                 for (Sone sone : sones) {
419                         freenetInterface.unregisterUsk(sone);
420                 }
421         }
422
423 }