Remove declared exception, it's never thrown.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneParser.java
1 /*
2  * Sone - SoneParser.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 static com.google.common.base.Optional.absent;
21 import static com.google.common.base.Optional.fromNullable;
22 import static com.google.common.base.Optional.of;
23
24 import java.io.InputStream;
25 import java.util.HashSet;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30
31 import net.pterodactylus.sone.data.Album;
32 import net.pterodactylus.sone.data.Client;
33 import net.pterodactylus.sone.data.Image;
34 import net.pterodactylus.sone.data.Post;
35 import net.pterodactylus.sone.data.PostReply;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Sone;
38 import net.pterodactylus.sone.data.impl.DefaultSone;
39 import net.pterodactylus.sone.database.Database;
40 import net.pterodactylus.sone.database.ImageBuilder.ImageCreated;
41 import net.pterodactylus.sone.database.PostBuilder;
42 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
43 import net.pterodactylus.sone.database.PostReplyBuilder;
44 import net.pterodactylus.sone.database.PostReplyBuilder.PostReplyCreated;
45 import net.pterodactylus.sone.database.memory.MemoryDatabase;
46 import net.pterodactylus.util.number.Numbers;
47 import net.pterodactylus.util.xml.SimpleXML;
48 import net.pterodactylus.util.xml.XML;
49
50 import com.google.common.base.Optional;
51 import com.google.common.collect.Maps;
52 import com.google.common.primitives.Ints;
53 import org.w3c.dom.Document;
54
55 /**
56  * Parses the inserted XML representation of a {@link Sone} into a Sone.
57  *
58  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
59  */
60 public class SoneParser {
61
62         private static final Logger logger = Logger.getLogger(SoneParser.class.getName());
63         private static final int MAX_PROTOCOL_VERSION = 0;
64
65         /**
66          * Parses a Sone from the given input stream and creates a new Sone from the
67          * parsed data.
68          *
69          * @param originalSone
70          *              The Sone to update
71          * @param soneInputStream
72          *              The input stream to parse the Sone from
73          * @return The parsed Sone
74          */
75         public Sone parseSone(Database database, Sone originalSone, InputStream soneInputStream) {
76                 /* TODO - impose a size limit? */
77
78                 Document document;
79                 /* XML parsing is not thread-safe. */
80                 synchronized (this) {
81                         document = XML.transformToDocument(soneInputStream);
82                 }
83                 if (document == null) {
84                         /* TODO - mark Sone as bad. */
85                         logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone.getId()));
86                         return null;
87                 }
88
89                 Optional<SimpleXML> soneXml = parseXml(originalSone, document);
90                 if (!soneXml.isPresent()) {
91                         logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", originalSone.getId()));
92                         return null;
93                 }
94
95                 Optional<Client> parsedClient = parseClient(originalSone, soneXml.get());
96                 Sone sone = new DefaultSone(database, originalSone.getId(), originalSone.isLocal(), parsedClient.or(originalSone.getClient()));
97
98                 Optional<Integer> protocolVersion = parseProtocolVersion(soneXml.get());
99                 if (protocolVersion.isPresent()) {
100                         if (protocolVersion.get() < 0) {
101                                 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion.get()));
102                                 return null;
103                         }
104                         if (protocolVersion.get() > MAX_PROTOCOL_VERSION) {
105                                 logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion.get()));
106                                 return null;
107                         }
108                 }
109
110                 String soneTime = soneXml.get().getValue("time", null);
111                 if (soneTime == null) {
112                         /* TODO - mark Sone as bad. */
113                         logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
114                         return null;
115                 }
116                 try {
117                         sone.setTime(Long.parseLong(soneTime));
118                 } catch (NumberFormatException nfe1) {
119                         /* TODO - mark Sone as bad. */
120                         logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
121                         return null;
122                 }
123
124                 SimpleXML profileXml = soneXml.get().getNode("profile");
125                 if (profileXml == null) {
126                         /* TODO - mark Sone as bad. */
127                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
128                         return null;
129                 }
130
131                 /* parse profile. */
132                 String profileFirstName = profileXml.getValue("first-name", null);
133                 String profileMiddleName = profileXml.getValue("middle-name", null);
134                 String profileLastName = profileXml.getValue("last-name", null);
135                 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
136                 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
137                 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
138                 Profile profile = new Profile(sone).modify().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName).update();
139                 profile.modify().setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear).update();
140                 /* avatar is processed after images are loaded. */
141                 String avatarId = profileXml.getValue("avatar", null);
142
143                 /* parse profile fields. */
144                 SimpleXML profileFieldsXml = profileXml.getNode("fields");
145                 if (profileFieldsXml != null) {
146                         for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
147                                 String fieldName = fieldXml.getValue("field-name", null);
148                                 String fieldValue = fieldXml.getValue("field-value", "");
149                                 if (fieldName == null) {
150                                         logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
151                                         return null;
152                                 }
153                                 try {
154                                         profile.addField(fieldName).setValue(fieldValue);
155                                 } catch (IllegalArgumentException iae1) {
156                                         logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
157                                         return null;
158                                 }
159                         }
160                 }
161
162                 /* parse posts. */
163                 SimpleXML postsXml = soneXml.get().getNode("posts");
164                 Set<Post> posts = new HashSet<Post>();
165                 if (postsXml == null) {
166                         /* TODO - mark Sone as bad. */
167                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
168                 } else {
169                         for (SimpleXML postXml : postsXml.getNodes("post")) {
170                                 String postId = postXml.getValue("id", null);
171                                 String postRecipientId = postXml.getValue("recipient", null);
172                                 String postTime = postXml.getValue("time", null);
173                                 String postText = postXml.getValue("text", null);
174                                 if ((postId == null) || (postTime == null) || (postText == null)) {
175                                         /* TODO - mark Sone as bad. */
176                                         logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
177                                         return null;
178                                 }
179                                 try {
180                                         PostBuilder postBuilder = sone.newPostBuilder();
181                                         /* TODO - parse time correctly. */
182                                         postBuilder.withId(postId).withTime(Long.parseLong(postTime)).withText(postText);
183                                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
184                                                 postBuilder.to(of(postRecipientId));
185                                         }
186                                         posts.add(postBuilder.build(Optional.<PostCreated>absent()));
187                                 } catch (NumberFormatException nfe1) {
188                                         /* TODO - mark Sone as bad. */
189                                         logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
190                                         return null;
191                                 }
192                         }
193                 }
194
195                 /* parse replies. */
196                 SimpleXML repliesXml = soneXml.get().getNode("replies");
197                 Set<PostReply> replies = new HashSet<PostReply>();
198                 if (repliesXml == null) {
199                         /* TODO - mark Sone as bad. */
200                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
201                 } else {
202                         for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
203                                 String replyId = replyXml.getValue("id", null);
204                                 String replyPostId = replyXml.getValue("post-id", null);
205                                 String replyTime = replyXml.getValue("time", null);
206                                 String replyText = replyXml.getValue("text", null);
207                                 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
208                                         /* TODO - mark Sone as bad. */
209                                         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));
210                                         return null;
211                                 }
212                                 try {
213                                         /* TODO - parse time correctly. */
214                                         PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(replyPostId).withId(replyId).withTime(Long.parseLong(replyTime)).withText(replyText);
215                                         replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
216                                 } catch (NumberFormatException nfe1) {
217                                         /* TODO - mark Sone as bad. */
218                                         logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
219                                         return null;
220                                 }
221                         }
222                 }
223
224                 /* parse liked post IDs. */
225                 SimpleXML likePostIdsXml = soneXml.get().getNode("post-likes");
226                 Set<String> likedPostIds = new HashSet<String>();
227                 if (likePostIdsXml == null) {
228                         /* TODO - mark Sone as bad. */
229                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
230                 } else {
231                         for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
232                                 String postId = likedPostIdXml.getValue();
233                                 likedPostIds.add(postId);
234                         }
235                 }
236
237                 /* parse liked reply IDs. */
238                 SimpleXML likeReplyIdsXml = soneXml.get().getNode("reply-likes");
239                 Set<String> likedReplyIds = new HashSet<String>();
240                 if (likeReplyIdsXml == null) {
241                         /* TODO - mark Sone as bad. */
242                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
243                 } else {
244                         for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
245                                 String replyId = likedReplyIdXml.getValue();
246                                 likedReplyIds.add(replyId);
247                         }
248                 }
249
250                 /* parse albums. */
251                 SimpleXML albumsXml = soneXml.get().getNode("albums");
252                 Map<String, Album> albums = Maps.newHashMap();
253                 if (albumsXml != null) {
254                         for (SimpleXML albumXml : albumsXml.getNodes("album")) {
255                                 String id = albumXml.getValue("id", null);
256                                 String parentId = albumXml.getValue("parent", null);
257                                 String title = albumXml.getValue("title", null);
258                                 String description = albumXml.getValue("description", "");
259                                 String albumImageId = albumXml.getValue("album-image", null);
260                                 if ((id == null) || (title == null) || (description == null)) {
261                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
262                                         return null;
263                                 }
264                                 Album parent = sone.getRootAlbum();
265                                 if (parentId != null) {
266                                         parent = albums.get(parentId);
267                                         if (parent == null) {
268                                                 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
269                                                 return null;
270                                         }
271                                 }
272                                 Album album = parent.newAlbumBuilder().withId(id).build().modify().setTitle(title).setDescription(description).update();
273                                 albums.put(album.getId(), album);
274                                 SimpleXML imagesXml = albumXml.getNode("images");
275                                 if (imagesXml != null) {
276                                         for (SimpleXML imageXml : imagesXml.getNodes("image")) {
277                                                 String imageId = imageXml.getValue("id", null);
278                                                 String imageCreationTimeString = imageXml.getValue("creation-time", null);
279                                                 String imageKey = imageXml.getValue("key", null);
280                                                 String imageTitle = imageXml.getValue("title", null);
281                                                 String imageDescription = imageXml.getValue("description", "");
282                                                 String imageWidthString = imageXml.getValue("width", null);
283                                                 String imageHeightString = imageXml.getValue("height", null);
284                                                 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
285                                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
286                                                         return null;
287                                                 }
288                                                 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
289                                                 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
290                                                 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
291                                                 if ((imageWidth < 1) || (imageHeight < 1)) {
292                                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
293                                                         return null;
294                                                 }
295                                                 Image image = album.newImageBuilder().withId(imageId).at(imageKey).created(creationTime).sized(imageWidth, imageHeight).build(Optional.<ImageCreated>absent());
296                                                 image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
297                                         }
298                                 }
299                                 album.modify().setAlbumImage(albumImageId).update();
300                         }
301                 }
302
303                 /* process avatar. */
304                 profile.setAvatar(fromNullable(avatarId));
305
306                 /* okay, apparently everything was parsed correctly. Now import. */
307                 sone.setProfile(profile);
308                 sone.setPosts(posts);
309                 sone.setReplies(replies);
310                 sone.setLikePostIds(likedPostIds);
311                 sone.setLikeReplyIds(likedReplyIds);
312
313                 return sone;
314         }
315
316         private Optional<Integer> parseProtocolVersion(SimpleXML soneXml) {
317                 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
318                 if (soneProtocolVersion == null) {
319                         logger.log(Level.INFO, "No protocol version found, assuming 0.");
320                         return absent();
321                 }
322                 return fromNullable(Ints.tryParse(soneProtocolVersion));
323         }
324
325         private Optional<SimpleXML> parseXml(Sone originalSone, Document document) {
326                 try {
327                         return fromNullable(SimpleXML.fromDocument(document));
328                 } catch (NullPointerException npe1) {
329                         /* for some reason, invalid XML can cause NPEs. */
330                         return absent();
331                 }
332         }
333
334         private Optional<Client> parseClient(Sone sone, SimpleXML soneXml) {
335                 SimpleXML clientXml = soneXml.getNode("client");
336                 if (clientXml == null) {
337                         return absent();
338                 }
339                 String clientName = clientXml.getValue("name", null);
340                 String clientVersion = clientXml.getValue("version", null);
341                 if ((clientName == null) || (clientVersion == null)) {
342                         logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
343                         return null;
344                 }
345                 return of(new Client(clientName, clientVersion));
346         }
347
348 }