e234965da331ef92f20f5fa1afe09c3577f068b9
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneParser.java
1 package net.pterodactylus.sone.core;
2
3 import static java.util.logging.Logger.getLogger;
4 import static net.pterodactylus.sone.utils.NumberParsers.parseInt;
5 import static net.pterodactylus.sone.utils.NumberParsers.parseLong;
6
7 import java.io.InputStream;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.HashSet;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.Set;
14 import java.util.logging.Level;
15 import java.util.logging.Logger;
16
17 import net.pterodactylus.sone.data.Album;
18 import net.pterodactylus.sone.data.Client;
19 import net.pterodactylus.sone.data.Image;
20 import net.pterodactylus.sone.data.Post;
21 import net.pterodactylus.sone.data.PostReply;
22 import net.pterodactylus.sone.data.Profile;
23 import net.pterodactylus.sone.data.Profile.DuplicateField;
24 import net.pterodactylus.sone.data.Sone;
25 import net.pterodactylus.sone.database.PostBuilder;
26 import net.pterodactylus.sone.database.PostReplyBuilder;
27 import net.pterodactylus.sone.database.SoneBuilder;
28 import net.pterodactylus.util.xml.SimpleXML;
29 import net.pterodactylus.util.xml.XML;
30
31 import org.w3c.dom.Document;
32
33 /**
34  * Parses a {@link Sone} from an XML {@link InputStream}.
35  *
36  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
37  */
38 public class SoneParser {
39
40         private static final Logger logger = getLogger("Sone.Parser");
41         private static final int MAX_PROTOCOL_VERSION = 0;
42         private final Core core;
43
44         public SoneParser(Core core) {
45                 this.core = core;
46         }
47
48         public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
49                 /* TODO - impose a size limit? */
50
51                 Document document;
52                 /* XML parsing is not thread-safe. */
53                 synchronized (this) {
54                         document = XML.transformToDocument(soneInputStream);
55                 }
56                 if (document == null) {
57                         /* TODO - mark Sone as bad. */
58                         logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
59                         return null;
60                 }
61
62                 SoneBuilder soneBuilder = core.soneBuilder().from(originalSone.getIdentity());
63                 if (originalSone.isLocal()) {
64                         soneBuilder = soneBuilder.local();
65                 }
66                 Sone sone = soneBuilder.build();
67
68                 SimpleXML soneXml;
69                 try {
70                         soneXml = SimpleXML.fromDocument(document);
71                 } catch (NullPointerException npe1) {
72                         /* for some reason, invalid XML can cause NPEs. */
73                         logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1);
74                         return null;
75                 }
76
77                 Integer protocolVersion = null;
78                 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
79                 if (soneProtocolVersion != null) {
80                         protocolVersion = parseInt(soneProtocolVersion, null);
81                 }
82                 if (protocolVersion == null) {
83                         logger.log(Level.INFO, "No protocol version found, assuming 0.");
84                         protocolVersion = 0;
85                 }
86
87                 if (protocolVersion < 0) {
88                         logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
89                         return null;
90                 }
91
92                 /* check for valid versions. */
93                 if (protocolVersion > MAX_PROTOCOL_VERSION) {
94                         logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
95                         return null;
96                 }
97
98                 String soneTime = soneXml.getValue("time", null);
99                 if (soneTime == null) {
100                         /* TODO - mark Sone as bad. */
101                         logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
102                         return null;
103                 }
104                 try {
105                         sone.setTime(Long.parseLong(soneTime));
106                 } catch (NumberFormatException nfe1) {
107                         /* TODO - mark Sone as bad. */
108                         logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
109                         return null;
110                 }
111
112                 SimpleXML clientXml = soneXml.getNode("client");
113                 if (clientXml != null) {
114                         String clientName = clientXml.getValue("name", null);
115                         String clientVersion = clientXml.getValue("version", null);
116                         if ((clientName == null) || (clientVersion == null)) {
117                                 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
118                                 return null;
119                         }
120                         sone.setClient(new Client(clientName, clientVersion));
121                 }
122
123                 SimpleXML profileXml = soneXml.getNode("profile");
124                 if (profileXml == null) {
125                         /* TODO - mark Sone as bad. */
126                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
127                         return null;
128                 }
129
130                 /* parse profile. */
131                 String profileFirstName = profileXml.getValue("first-name", null);
132                 String profileMiddleName = profileXml.getValue("middle-name", null);
133                 String profileLastName = profileXml.getValue("last-name", null);
134                 Integer profileBirthDay = parseInt(profileXml.getValue("birth-day", ""), null);
135                 Integer profileBirthMonth = parseInt(profileXml.getValue("birth-month", ""), null);
136                 Integer profileBirthYear = parseInt(profileXml.getValue("birth-year", ""), null);
137                 Profile profile = new Profile(sone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
138                 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
139                 /* avatar is processed after images are loaded. */
140                 String avatarId = profileXml.getValue("avatar", null);
141
142                 /* parse profile fields. */
143                 SimpleXML profileFieldsXml = profileXml.getNode("fields");
144                 if (profileFieldsXml != null) {
145                         for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
146                                 String fieldName = fieldXml.getValue("field-name", null);
147                                 String fieldValue = fieldXml.getValue("field-value", "");
148                                 if (fieldName == null) {
149                                         logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
150                                         return null;
151                                 }
152                                 try {
153                                         profile.addField(fieldName.trim()).setValue(fieldValue);
154                                 } catch (DuplicateField df1) {
155                                         logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), df1);
156                                         return null;
157                                 }
158                         }
159                 }
160
161                 /* parse posts. */
162                 SimpleXML postsXml = soneXml.getNode("posts");
163                 Set<Post> posts = new HashSet<Post>();
164                 if (postsXml == null) {
165                         /* TODO - mark Sone as bad. */
166                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
167                 } else {
168                         for (SimpleXML postXml : postsXml.getNodes("post")) {
169                                 String postId = postXml.getValue("id", null);
170                                 String postRecipientId = postXml.getValue("recipient", null);
171                                 String postTime = postXml.getValue("time", null);
172                                 String postText = postXml.getValue("text", null);
173                                 if ((postId == null) || (postTime == null) || (postText == null)) {
174                                         /* TODO - mark Sone as bad. */
175                                         logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
176                                         return null;
177                                 }
178                                 try {
179                                         PostBuilder postBuilder = core.postBuilder();
180                                         /* TODO - parse time correctly. */
181                                         postBuilder.withId(postId).from(sone.getId()).withTime(Long.parseLong(postTime)).withText(postText);
182                                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
183                                                 postBuilder.to(postRecipientId);
184                                         }
185                                         posts.add(postBuilder.build());
186                                 } catch (NumberFormatException nfe1) {
187                                         /* TODO - mark Sone as bad. */
188                                         logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
189                                         return null;
190                                 }
191                         }
192                 }
193
194                 /* parse replies. */
195                 SimpleXML repliesXml = soneXml.getNode("replies");
196                 Set<PostReply> replies = new HashSet<PostReply>();
197                 if (repliesXml == null) {
198                         /* TODO - mark Sone as bad. */
199                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
200                 } else {
201                         for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
202                                 String replyId = replyXml.getValue("id", null);
203                                 String replyPostId = replyXml.getValue("post-id", null);
204                                 String replyTime = replyXml.getValue("time", null);
205                                 String replyText = replyXml.getValue("text", null);
206                                 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
207                                         /* TODO - mark Sone as bad. */
208                                         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));
209                                         return null;
210                                 }
211                                 try {
212                                         PostReplyBuilder postReplyBuilder = core.postReplyBuilder();
213                                         /* TODO - parse time correctly. */
214                                         postReplyBuilder.withId(replyId).from(sone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText);
215                                         replies.add(postReplyBuilder.build());
216                                 } catch (NumberFormatException nfe1) {
217                                         /* TODO - mark Sone as bad. */
218                                         logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
219                                         return null;
220                                 }
221                         }
222                 }
223
224                 /* parse liked post IDs. */
225                 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
226                 Set<String> likedPostIds = new HashSet<String>();
227                 if (likePostIdsXml == null) {
228                         /* TODO - mark Sone as bad. */
229                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
230                 } else {
231                         for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
232                                 String postId = likedPostIdXml.getValue();
233                                 likedPostIds.add(postId);
234                         }
235                 }
236
237                 /* parse liked reply IDs. */
238                 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
239                 Set<String> likedReplyIds = new HashSet<String>();
240                 if (likeReplyIdsXml == null) {
241                         /* TODO - mark Sone as bad. */
242                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
243                 } else {
244                         for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
245                                 String replyId = likedReplyIdXml.getValue();
246                                 likedReplyIds.add(replyId);
247                         }
248                 }
249
250                 /* parse albums. */
251                 SimpleXML albumsXml = soneXml.getNode("albums");
252                 Map<String, Image> allImages = new HashMap<String, Image>();
253                 List<Album> topLevelAlbums = new ArrayList<Album>();
254                 if (albumsXml != null) {
255                         for (SimpleXML albumXml : albumsXml.getNodes("album")) {
256                                 String id = albumXml.getValue("id", null);
257                                 String parentId = albumXml.getValue("parent", null);
258                                 String title = albumXml.getValue("title", null);
259                                 String description = albumXml.getValue("description", "");
260                                 String albumImageId = albumXml.getValue("album-image", null);
261                                 if ((id == null) || (title == null)) {
262                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
263                                         return null;
264                                 }
265                                 Album parent = null;
266                                 if (parentId != null) {
267                                         parent = core.getAlbum(parentId);
268                                         if (parent == null) {
269                                                 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
270                                                 return null;
271                                         }
272                                 }
273                                 Album album = core.albumBuilder()
274                                                 .withId(id)
275                                                 .by(sone)
276                                                 .build()
277                                                 .modify()
278                                                 .setTitle(title)
279                                                 .setDescription(description)
280                                                 .update();
281                                 if (parent != null) {
282                                         parent.addAlbum(album);
283                                 } else {
284                                         topLevelAlbums.add(album);
285                                 }
286                                 SimpleXML imagesXml = albumXml.getNode("images");
287                                 if (imagesXml != null) {
288                                         for (SimpleXML imageXml : imagesXml.getNodes("image")) {
289                                                 String imageId = imageXml.getValue("id", null);
290                                                 String imageCreationTimeString = imageXml.getValue("creation-time", null);
291                                                 String imageKey = imageXml.getValue("key", null);
292                                                 String imageTitle = imageXml.getValue("title", null);
293                                                 String imageDescription = imageXml.getValue("description", "");
294                                                 String imageWidthString = imageXml.getValue("width", null);
295                                                 String imageHeightString = imageXml.getValue("height", null);
296                                                 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
297                                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
298                                                         return null;
299                                                 }
300                                                 long creationTime = parseLong(imageCreationTimeString, 0L);
301                                                 int imageWidth = parseInt(imageWidthString, 0);
302                                                 int imageHeight = parseInt(imageHeightString, 0);
303                                                 if ((imageWidth < 1) || (imageHeight < 1)) {
304                                                         logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
305                                                         return null;
306                                                 }
307                                                 Image image = core.imageBuilder().withId(imageId).build().modify().setSone(sone).setKey(imageKey).setCreationTime(creationTime).update();
308                                                 image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
309                                                 image = image.modify().setWidth(imageWidth).setHeight(imageHeight).update();
310                                                 album.addImage(image);
311                                                 allImages.put(imageId, image);
312                                         }
313                                 }
314                                 album.modify().setAlbumImage(albumImageId).update();
315                         }
316                 }
317
318                 /* process avatar. */
319                 if (avatarId != null) {
320                         profile.setAvatar(allImages.get(avatarId));
321                 }
322
323                 /* okay, apparently everything was parsed correctly. Now import. */
324                 /* atomic setter operation on the Sone. */
325                 synchronized (sone) {
326                         sone.setProfile(profile);
327                         sone.setPosts(posts);
328                         sone.setReplies(replies);
329                         sone.setLikePostIds(likedPostIds);
330                         sone.setLikeReplyIds(likedReplyIds);
331                         for (Album album : topLevelAlbums) {
332                                 sone.getRootAlbum().addAlbum(album);
333                         }
334                 }
335
336                 return sone;
337
338         }
339
340 }