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