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