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