Store request URI in yet unknown Sones when parsing.
[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.util.HashSet;
23 import java.util.Set;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26
27 import net.pterodactylus.sone.data.Post;
28 import net.pterodactylus.sone.data.Profile;
29 import net.pterodactylus.sone.data.Reply;
30 import net.pterodactylus.sone.data.Sone;
31 import net.pterodactylus.util.io.Closer;
32 import net.pterodactylus.util.logging.Logging;
33 import net.pterodactylus.util.service.AbstractService;
34 import net.pterodactylus.util.xml.SimpleXML;
35 import net.pterodactylus.util.xml.XML;
36
37 import org.w3c.dom.Document;
38
39 import freenet.client.FetchResult;
40 import freenet.keys.FreenetURI;
41 import freenet.support.api.Bucket;
42
43 /**
44  * The Sone downloader is responsible for download Sones as they are updated.
45  *
46  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
47  */
48 public class SoneDownloader extends AbstractService {
49
50         /** The logger. */
51         private static final Logger logger = Logging.getLogger(SoneDownloader.class);
52
53         /** The core. */
54         private final Core core;
55
56         /** The Freenet interface. */
57         private final FreenetInterface freenetInterface;
58
59         /** The sones to update. */
60         private final Set<Sone> sones = new HashSet<Sone>();
61
62         /**
63          * Creates a new Sone downloader.
64          *
65          * @param core
66          *            The core
67          * @param freenetInterface
68          *            The Freenet interface
69          */
70         public SoneDownloader(Core core, FreenetInterface freenetInterface) {
71                 super("Sone Downloader");
72                 this.core = core;
73                 this.freenetInterface = freenetInterface;
74         }
75
76         //
77         // ACTIONS
78         //
79
80         /**
81          * Adds the given Sone to the set of Sones that will be watched for updates.
82          *
83          * @param sone
84          *            The Sone to add
85          */
86         public void addSone(Sone sone) {
87                 if (sones.add(sone)) {
88                         freenetInterface.registerUsk(sone, this);
89                 }
90         }
91
92         /**
93          * Removes the given Sone from the downloader.
94          *
95          * @param sone
96          *            The Sone to stop watching
97          */
98         public void removeSone(Sone sone) {
99                 if (sones.remove(sone)) {
100                         freenetInterface.unregisterUsk(sone);
101                 }
102         }
103
104         /**
105          * Fetches the updated Sone. This method is a callback method for
106          * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
107          *
108          * @param sone
109          *            The Sone to fetch
110          */
111         public void fetchSone(Sone sone) {
112                 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
113                 FreenetURI requestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
114                 FetchResult fetchResult = freenetInterface.fetchUri(requestUri);
115                 logger.log(Level.FINEST, "Got %d bytes back.", fetchResult.size());
116                 Sone parsedSone = parseSone(sone, fetchResult, requestUri);
117                 if (parsedSone != null) {
118                         core.addSone(parsedSone);
119                 }
120         }
121
122         /**
123          * Parses a Sone from a fetch result.
124          *
125          * @param originalSone
126          *            The sone to parse, or {@code null} if the Sone is yet unknown
127          * @param fetchResult
128          *            The fetch result
129          * @param requestUri
130          *            The requested URI
131          * @return The parsed Sone, or {@code null} if the Sone could not be parsed
132          */
133         public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
134                 logger.log(Level.FINEST, "Persing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), originalSone });
135                 /* TODO - impose a size limit? */
136                 InputStream xmlInputStream = null;
137                 Bucket xmlBucket = null;
138                 Sone sone;
139                 try {
140                         xmlBucket = fetchResult.asBucket();
141                         xmlInputStream = xmlBucket.getInputStream();
142                         Document document = XML.transformToDocument(xmlInputStream);
143                         SimpleXML soneXml;
144                         try {
145                                 soneXml = SimpleXML.fromDocument(document);
146                         } catch (NullPointerException npe1) {
147                                 /* for some reason, invalid XML can cause NPEs. */
148                                 logger.log(Level.WARNING, "XML for Sone " + originalSone + " can not be parsed!", npe1);
149                                 return null;
150                         }
151
152                         /* check ID. */
153                         String soneId = soneXml.getValue("id", null);
154                         if ((originalSone != null) && !originalSone.getId().equals(soneId)) {
155                                 /* TODO - mark Sone as bad. */
156                                 logger.log(Level.WARNING, "Downloaded ID for Sone %s (%s) does not match known ID (%s)!", new Object[] { originalSone, originalSone.getId(), soneId });
157                                 return null;
158                         }
159
160                         /* load Sone from core. */
161                         sone = originalSone;
162                         if (sone == null) {
163                                 sone = core.getSone(soneId).setRequestUri(requestUri.setMetaString(new String[] {}));
164                         }
165
166                         String soneName = soneXml.getValue("name", null);
167                         if (soneName == null) {
168                                 /* TODO - mark Sone as bad. */
169                                 logger.log(Level.WARNING, "Downloaded name for Sone %s was null!", new Object[] { sone });
170                                 return null;
171                         }
172
173                         SimpleXML profileXml = soneXml.getNode("profile");
174                         if (profileXml == null) {
175                                 /* TODO - mark Sone as bad. */
176                                 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
177                                 return null;
178                         }
179
180                         /* parse profile. */
181                         String profileFirstName = profileXml.getValue("first-name", null);
182                         String profileMiddleName = profileXml.getValue("middle-name", null);
183                         String profileLastName = profileXml.getValue("last-name", null);
184                         Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
185
186                         /* parse posts. */
187                         SimpleXML postsXml = soneXml.getNode("posts");
188                         if (postsXml == null) {
189                                 /* TODO - mark Sone as bad. */
190                                 logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
191                                 return null;
192                         }
193
194                         Set<Post> posts = new HashSet<Post>();
195                         for (SimpleXML postXml : postsXml.getNodes("post")) {
196                                 String postId = postXml.getValue("id", null);
197                                 String postTime = postXml.getValue("time", null);
198                                 String postText = postXml.getValue("text", null);
199                                 if ((postId == null) || (postTime == null) || (postText == null)) {
200                                         /* TODO - mark Sone as bad. */
201                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
202                                         return null;
203                                 }
204                                 try {
205                                         posts.add(core.getPost(postId).setSone(sone).setTime(Long.parseLong(postTime)).setText(postText));
206                                 } catch (NumberFormatException nfe1) {
207                                         /* TODO - mark Sone as bad. */
208                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
209                                         return null;
210                                 }
211                         }
212
213                         /* parse replies. */
214                         SimpleXML repliesXml = soneXml.getNode("replies");
215                         if (repliesXml == null) {
216                                 /* TODO - mark Sone as bad. */
217                                 logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
218                                 return null;
219                         }
220
221                         Set<Reply> replies = new HashSet<Reply>();
222                         for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
223                                 String replyId = replyXml.getValue("id", null);
224                                 String replyPostId = replyXml.getValue("post-id", null);
225                                 String replyTime = replyXml.getValue("time", null);
226                                 String replyText = replyXml.getValue("text", null);
227                                 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
228                                         /* TODO - mark Sone as bad. */
229                                         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 });
230                                         return null;
231                                 }
232                                 try {
233                                         replies.add(core.getReply(replyId).setSone(sone).setPost(core.getPost(replyPostId)).setTime(Long.parseLong(replyTime)).setText(replyText));
234                                 } catch (NumberFormatException nfe1) {
235                                         /* TODO - mark Sone as bad. */
236                                         logger.log(Level.WARNING, "Downloaded reply for Sone %s with invalid time: %s", new Object[] { sone, replyTime });
237                                         return null;
238                                 }
239                         }
240
241                         /* okay, apparently everything was parsed correctly. Now import. */
242                         /* atomic setter operation on the Sone. */
243                         synchronized (sone) {
244                                 sone.setProfile(profile);
245                                 sone.setPosts(posts);
246                                 sone.setReplies(replies);
247                                 sone.setModificationCounter(0);
248                         }
249                 } catch (IOException ioe1) {
250                         logger.log(Level.WARNING, "Could not read XML file from " + originalSone + "!", ioe1);
251                         return null;
252                 } finally {
253                         if (xmlBucket != null) {
254                                 xmlBucket.free();
255                         }
256                         Closer.close(xmlInputStream);
257                 }
258                 return sone;
259         }
260
261         //
262         // SERVICE METHODS
263         //
264
265         /**
266          * {@inheritDoc}
267          */
268         @Override
269         protected void serviceStop() {
270                 for (Sone sone : sones) {
271                         freenetInterface.unregisterUsk(sone);
272                 }
273         }
274
275 }