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