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