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