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