Remove unused method.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneDownloader.java
1 /*
2  * Sone - SoneDownloader.java - Copyright © 2010–2013 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.InputStream;
21 import java.net.MalformedURLException;
22 import java.util.ArrayList;
23 import java.util.HashSet;
24 import java.util.List;
25 import java.util.Set;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sone.core.FreenetInterface.Fetched;
30 import net.pterodactylus.sone.data.Album;
31 import net.pterodactylus.sone.data.Client;
32 import net.pterodactylus.sone.data.Image;
33 import net.pterodactylus.sone.data.Post;
34 import net.pterodactylus.sone.data.PostReply;
35 import net.pterodactylus.sone.data.Profile;
36 import net.pterodactylus.sone.data.Sone;
37 import net.pterodactylus.sone.data.Sone.SoneStatus;
38 import net.pterodactylus.sone.data.SoneImpl;
39 import net.pterodactylus.sone.database.PostBuilder;
40 import net.pterodactylus.sone.database.PostReplyBuilder;
41 import net.pterodactylus.util.io.Closer;
42 import net.pterodactylus.util.logging.Logging;
43 import net.pterodactylus.util.number.Numbers;
44 import net.pterodactylus.util.service.AbstractService;
45 import net.pterodactylus.util.xml.SimpleXML;
46 import net.pterodactylus.util.xml.XML;
47
48 import org.w3c.dom.Document;
49
50 import freenet.client.FetchResult;
51 import freenet.keys.FreenetURI;
52 import freenet.support.api.Bucket;
53
54 /**
55  * The Sone downloader is responsible for download Sones as they are updated.
56  *
57  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
58  */
59 public class SoneDownloader extends AbstractService {
60
61         /** The logger. */
62         private static final Logger logger = Logging.getLogger(SoneDownloader.class);
63
64         /** The maximum protocol version. */
65         private static final int MAX_PROTOCOL_VERSION = 0;
66
67         /** The core. */
68         private final Core core;
69
70         /** The Freenet interface. */
71         private final FreenetInterface freenetInterface;
72
73         /** The sones to update. */
74         private final Set<Sone> sones = new HashSet<Sone>();
75
76         /**
77          * Creates a new Sone downloader.
78          *
79          * @param core
80          *            The core
81          * @param freenetInterface
82          *            The Freenet interface
83          */
84         public SoneDownloader(Core core, FreenetInterface freenetInterface) {
85                 super("Sone Downloader", false);
86                 this.core = core;
87                 this.freenetInterface = freenetInterface;
88         }
89
90         //
91         // ACTIONS
92         //
93
94         /**
95          * Adds the given Sone to the set of Sones that will be watched for updates.
96          *
97          * @param sone
98          *            The Sone to add
99          */
100         public void addSone(Sone sone) {
101                 if (!sones.add(sone)) {
102                         freenetInterface.unregisterUsk(sone);
103                 }
104                 freenetInterface.registerUsk(sone, this);
105         }
106
107         /**
108          * Fetches the updated Sone. This method is a callback method for
109          * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
110          *
111          * @param sone
112          *            The Sone to fetch
113          */
114         public void fetchSone(Sone sone) {
115                 fetchSone(sone, sone.getRequestUri().sskForUSK());
116         }
117
118         /**
119          * Fetches the updated Sone. This method can be used to fetch a Sone from a
120          * specific URI.
121          *
122          * @param sone
123          *            The Sone to fetch
124          * @param soneUri
125          *            The URI to fetch the Sone from
126          */
127         public void fetchSone(Sone sone, FreenetURI soneUri) {
128                 fetchSone(sone, soneUri, false);
129         }
130
131         /**
132          * Fetches the Sone from the given URI.
133          *
134          * @param sone
135          *            The Sone to fetch
136          * @param soneUri
137          *            The URI of the Sone to fetch
138          * @param fetchOnly
139          *            {@code true} to only fetch and parse the Sone, {@code false}
140          *            to {@link Core#updateSone(Sone) update} it in the core
141          * @return The downloaded Sone, or {@code null} if the Sone could not be
142          *         downloaded
143          */
144         public Sone fetchSone(Sone sone, FreenetURI soneUri, boolean fetchOnly) {
145                 logger.log(Level.FINE, String.format("Starting fetch for Sone “%s” from %s…", sone, soneUri));
146                 FreenetURI requestUri = soneUri.setMetaString(new String[] { "sone.xml" });
147                 sone.setStatus(SoneStatus.downloading);
148                 try {
149                         Fetched fetchResults = freenetInterface.fetchUri(requestUri);
150                         if (fetchResults == null) {
151                                 /* TODO - mark Sone as bad. */
152                                 return null;
153                         }
154                         logger.log(Level.FINEST, String.format("Got %d bytes back.", fetchResults.getFetchResult().size()));
155                         Sone parsedSone = parseSone(sone, fetchResults.getFetchResult(), fetchResults.getFreenetUri());
156                         if (parsedSone != null) {
157                                 if (!fetchOnly) {
158                                         parsedSone.setStatus((parsedSone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
159                                         core.updateSone(parsedSone);
160                                         addSone(parsedSone);
161                                 }
162                         }
163                         return parsedSone;
164                 } finally {
165                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
166                 }
167         }
168
169         /**
170          * Parses a Sone from a fetch result.
171          *
172          * @param originalSone
173          *            The sone to parse, or {@code null} if the Sone is yet unknown
174          * @param fetchResult
175          *            The fetch result
176          * @param requestUri
177          *            The requested URI
178          * @return The parsed Sone, or {@code null} if the Sone could not be parsed
179          */
180         public Sone parseSone(Sone originalSone, FetchResult fetchResult, FreenetURI requestUri) {
181                 logger.log(Level.FINEST, String.format("Parsing FetchResult (%d bytes, %s) for %s…", fetchResult.size(), fetchResult.getMimeType(), originalSone));
182                 Bucket soneBucket = fetchResult.asBucket();
183                 InputStream soneInputStream = null;
184                 try {
185                         soneInputStream = soneBucket.getInputStream();
186                         Sone parsedSone = parseSone(originalSone, soneInputStream);
187                         if (parsedSone != null) {
188                                 parsedSone.setLatestEdition(requestUri.getEdition());
189                                 if (requestUri.getKeyType().equals("USK")) {
190                                         parsedSone.setRequestUri(requestUri.setMetaString(new String[0]));
191                                 } else {
192                                         parsedSone.setRequestUri(requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]));
193                                 }
194                         }
195                         return parsedSone;
196                 } catch (Exception e1) {
197                         logger.log(Level.WARNING, String.format("Could not parse Sone from %s!", requestUri), e1);
198                 } finally {
199                         Closer.close(soneInputStream);
200                         soneBucket.free();
201                 }
202                 return null;
203         }
204
205         /**
206          * Parses a Sone from the given input stream and creates a new Sone from the
207          * parsed data.
208          *
209          * @param originalSone
210          *            The Sone to update
211          * @param soneInputStream
212          *            The input stream to parse the Sone from
213          * @return The parsed Sone
214          * @throws SoneException
215          *             if a parse error occurs, or the protocol is invalid
216          */
217         public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
218                 /* TODO - impose a size limit? */
219
220                 Document document;
221                 /* XML parsing is not thread-safe. */
222                 synchronized (this) {
223                         document = XML.transformToDocument(soneInputStream);
224                 }
225                 if (document == null) {
226                         /* TODO - mark Sone as bad. */
227                         logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
228                         return null;
229                 }
230
231                 Sone sone = new SoneImpl(originalSone.getId(), originalSone.isLocal()).setIdentity(originalSone.getIdentity());
232
233                 SimpleXML soneXml;
234                 try {
235                         soneXml = SimpleXML.fromDocument(document);
236                 } catch (NullPointerException npe1) {
237                         /* for some reason, invalid XML can cause NPEs. */
238                         logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1);
239                         return null;
240                 }
241
242                 Integer protocolVersion = null;
243                 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
244                 if (soneProtocolVersion != null) {
245                         protocolVersion = Numbers.safeParseInteger(soneProtocolVersion);
246                 }
247                 if (protocolVersion == null) {
248                         logger.log(Level.INFO, "No protocol version found, assuming 0.");
249                         protocolVersion = 0;
250                 }
251
252                 if (protocolVersion < 0) {
253                         logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
254                         return null;
255                 }
256
257                 /* check for valid versions. */
258                 if (protocolVersion > MAX_PROTOCOL_VERSION) {
259                         logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
260                         return null;
261                 }
262
263                 String soneTime = soneXml.getValue("time", null);
264                 if (soneTime == null) {
265                         /* TODO - mark Sone as bad. */
266                         logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
267                         return null;
268                 }
269                 try {
270                         sone.setTime(Long.parseLong(soneTime));
271                 } catch (NumberFormatException nfe1) {
272                         /* TODO - mark Sone as bad. */
273                         logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
274                         return null;
275                 }
276
277                 SimpleXML clientXml = soneXml.getNode("client");
278                 if (clientXml != null) {
279                         String clientName = clientXml.getValue("name", null);
280                         String clientVersion = clientXml.getValue("version", null);
281                         if ((clientName == null) || (clientVersion == null)) {
282                                 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
283                                 return null;
284                         }
285                         sone.setClient(new Client(clientName, clientVersion));
286                 }
287
288                 String soneRequestUri = soneXml.getValue("request-uri", null);
289                 if (soneRequestUri != null) {
290                         try {
291                                 sone.setRequestUri(new FreenetURI(soneRequestUri));
292                         } catch (MalformedURLException mue1) {
293                                 /* TODO - mark Sone as bad. */
294                                 logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid request URI: %s", sone, soneRequestUri), mue1);
295                                 return null;
296                         }
297                 }
298
299                 if (originalSone.getInsertUri() != null) {
300                         sone.setInsertUri(originalSone.getInsertUri());
301                 }
302
303                 SimpleXML profileXml = soneXml.getNode("profile");
304                 if (profileXml == null) {
305                         /* TODO - mark Sone as bad. */
306                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
307                         return null;
308                 }
309
310                 /* parse profile. */
311                 String profileFirstName = profileXml.getValue("first-name", null);
312                 String profileMiddleName = profileXml.getValue("middle-name", null);
313                 String profileLastName = profileXml.getValue("last-name", null);
314                 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
315                 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
316                 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
317                 Profile profile = new Profile(sone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
318                 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
319                 /* avatar is processed after images are loaded. */
320                 String avatarId = profileXml.getValue("avatar", null);
321
322                 /* parse profile fields. */
323                 SimpleXML profileFieldsXml = profileXml.getNode("fields");
324                 if (profileFieldsXml != null) {
325                         for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
326                                 String fieldName = fieldXml.getValue("field-name", null);
327                                 String fieldValue = fieldXml.getValue("field-value", "");
328                                 if (fieldName == null) {
329                                         logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
330                                         return null;
331                                 }
332                                 try {
333                                         profile.addField(fieldName).setValue(fieldValue);
334                                 } catch (IllegalArgumentException iae1) {
335                                         logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
336                                         return null;
337                                 }
338                         }
339                 }
340
341                 /* parse posts. */
342                 SimpleXML postsXml = soneXml.getNode("posts");
343                 Set<Post> posts = new HashSet<Post>();
344                 if (postsXml == null) {
345                         /* TODO - mark Sone as bad. */
346                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
347                 } else {
348                         for (SimpleXML postXml : postsXml.getNodes("post")) {
349                                 String postId = postXml.getValue("id", null);
350                                 String postRecipientId = postXml.getValue("recipient", null);
351                                 String postTime = postXml.getValue("time", null);
352                                 String postText = postXml.getValue("text", null);
353                                 if ((postId == null) || (postTime == null) || (postText == null)) {
354                                         /* TODO - mark Sone as bad. */
355                                         logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
356                                         return null;
357                                 }
358                                 try {
359                                         PostBuilder postBuilder = core.postBuilder();
360                                         /* TODO - parse time correctly. */
361                                         postBuilder.withId(postId).from(sone.getId()).withTime(Long.parseLong(postTime)).withText(postText);
362                                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
363                                                 postBuilder.to(postRecipientId);
364                                         }
365                                         posts.add(postBuilder.build());
366                                 } catch (NumberFormatException nfe1) {
367                                         /* TODO - mark Sone as bad. */
368                                         logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
369                                         return null;
370                                 }
371                         }
372                 }
373
374                 /* parse replies. */
375                 SimpleXML repliesXml = soneXml.getNode("replies");
376                 Set<PostReply> replies = new HashSet<PostReply>();
377                 if (repliesXml == null) {
378                         /* TODO - mark Sone as bad. */
379                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
380                 } else {
381                         for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
382                                 String replyId = replyXml.getValue("id", null);
383                                 String replyPostId = replyXml.getValue("post-id", null);
384                                 String replyTime = replyXml.getValue("time", null);
385                                 String replyText = replyXml.getValue("text", null);
386                                 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
387                                         /* TODO - mark Sone as bad. */
388                                         logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with missing data! ID: %s, Post: %s, Time: %s, Text: %s", sone, replyId, replyPostId, replyTime, replyText));
389                                         return null;
390                                 }
391                                 try {
392                                         PostReplyBuilder postReplyBuilder = core.postReplyBuilder();
393                                         /* TODO - parse time correctly. */
394                                         postReplyBuilder.withId(replyId).from(sone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText);
395                                         replies.add(postReplyBuilder.build());
396                                 } catch (NumberFormatException nfe1) {
397                                         /* TODO - mark Sone as bad. */
398                                         logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
399                                         return null;
400                                 }
401                         }
402                 }
403
404                 /* parse liked post IDs. */
405                 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
406                 Set<String> likedPostIds = new HashSet<String>();
407                 if (likePostIdsXml == null) {
408                         /* TODO - mark Sone as bad. */
409                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
410                 } else {
411                         for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
412                                 String postId = likedPostIdXml.getValue();
413                                 likedPostIds.add(postId);
414                         }
415                 }
416
417                 /* parse liked reply IDs. */
418                 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
419                 Set<String> likedReplyIds = new HashSet<String>();
420                 if (likeReplyIdsXml == null) {
421                         /* TODO - mark Sone as bad. */
422                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
423                 } else {
424                         for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
425                                 String replyId = likedReplyIdXml.getValue();
426                                 likedReplyIds.add(replyId);
427                         }
428                 }
429
430                 /* parse albums. */
431                 SimpleXML albumsXml = soneXml.getNode("albums");
432                 List<Album> topLevelAlbums = new ArrayList<Album>();
433                 if (albumsXml != null) {
434                         for (SimpleXML albumXml : albumsXml.getNodes("album")) {
435                                 String id = albumXml.getValue("id", null);
436                                 String parentId = albumXml.getValue("parent", null);
437                                 String title = albumXml.getValue("title", null);
438                                 String description = albumXml.getValue("description", "");
439                                 String albumImageId = albumXml.getValue("album-image", null);
440                                 if ((id == null) || (title == null) || (description == null)) {
441                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
442                                         return null;
443                                 }
444                                 Album parent = null;
445                                 if (parentId != null) {
446                                         parent = core.getAlbum(parentId, false);
447                                         if (parent == null) {
448                                                 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
449                                                 return null;
450                                         }
451                                 }
452                                 Album album = core.getAlbum(id).setSone(sone).modify().setTitle(title).setDescription(description).update();
453                                 if (parent != null) {
454                                         parent.addAlbum(album);
455                                 } else {
456                                         topLevelAlbums.add(album);
457                                 }
458                                 SimpleXML imagesXml = albumXml.getNode("images");
459                                 if (imagesXml != null) {
460                                         for (SimpleXML imageXml : imagesXml.getNodes("image")) {
461                                                 String imageId = imageXml.getValue("id", null);
462                                                 String imageCreationTimeString = imageXml.getValue("creation-time", null);
463                                                 String imageKey = imageXml.getValue("key", null);
464                                                 String imageTitle = imageXml.getValue("title", null);
465                                                 String imageDescription = imageXml.getValue("description", "");
466                                                 String imageWidthString = imageXml.getValue("width", null);
467                                                 String imageHeightString = imageXml.getValue("height", null);
468                                                 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
469                                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
470                                                         return null;
471                                                 }
472                                                 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
473                                                 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
474                                                 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
475                                                 if ((imageWidth < 1) || (imageHeight < 1)) {
476                                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
477                                                         return null;
478                                                 }
479                                                 Image image = core.getImage(imageId).modify().setSone(sone).setKey(imageKey).setCreationTime(creationTime).update();
480                                                 image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
481                                                 image = image.modify().setWidth(imageWidth).setHeight(imageHeight).update();
482                                                 album.addImage(image);
483                                         }
484                                 }
485                                 album.modify().setAlbumImage(albumImageId).update();
486                         }
487                 }
488
489                 /* process avatar. */
490                 if (avatarId != null) {
491                         profile.setAvatar(core.getImage(avatarId, false));
492                 }
493
494                 /* okay, apparently everything was parsed correctly. Now import. */
495                 /* atomic setter operation on the Sone. */
496                 synchronized (sone) {
497                         sone.setProfile(profile);
498                         sone.setPosts(posts);
499                         sone.setReplies(replies);
500                         sone.setLikePostIds(likedPostIds);
501                         sone.setLikeReplyIds(likedReplyIds);
502                         for (Album album : topLevelAlbums) {
503                                 sone.getRootAlbum().addAlbum(album);
504                         }
505                 }
506
507                 return sone;
508         }
509
510         //
511         // SERVICE METHODS
512         //
513
514         /**
515          * {@inheritDoc}
516          */
517         @Override
518         protected void serviceStop() {
519                 for (Sone sone : sones) {
520                         freenetInterface.unregisterUsk(sone);
521                 }
522         }
523
524         public class FetchSoneWithUri implements Runnable {
525
526                 private final Sone sone;
527
528                 public FetchSoneWithUri(Sone sone) {
529                         this.sone = sone;
530                 }
531
532                 @Override
533                 public void run() {
534                         fetchSone(sone, sone.getRequestUri());
535                 }
536
537         }
538
539         public class FetchSone implements Runnable {
540
541                 private final Sone sone;
542
543                 public FetchSone(Sone sone) {
544                         this.sone = sone;
545                 }
546
547                 @Override
548                 public void run() {
549                         fetchSone(sone);
550                 }
551
552         }
553
554 }