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