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