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