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