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