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