Use different method to create a local Sone.
[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.Sone;
24 import net.pterodactylus.sone.database.PostBuilder;
25 import net.pterodactylus.sone.database.PostReplyBuilder;
26 import net.pterodactylus.sone.database.SoneBuilder;
27 import net.pterodactylus.util.xml.SimpleXML;
28 import net.pterodactylus.util.xml.XML;
29
30 import org.w3c.dom.Document;
31
32 /**
33  * Parses a {@link Sone} from an XML {@link InputStream}.
34  *
35  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
36  */
37 public class SoneParser {
38
39         private static final Logger logger = getLogger("Sone.Parser");
40         private static final int MAX_PROTOCOL_VERSION = 0;
41         private final Core core;
42
43         public SoneParser(Core core) {
44                 this.core = core;
45         }
46
47         public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
48                 /* TODO - impose a size limit? */
49
50                 Document document;
51                 /* XML parsing is not thread-safe. */
52                 synchronized (this) {
53                         document = XML.transformToDocument(soneInputStream);
54                 }
55                 if (document == null) {
56                         /* TODO - mark Sone as bad. */
57                         logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
58                         return null;
59                 }
60
61                 SoneBuilder soneBuilder = core.soneBuilder().from(originalSone.getIdentity());
62
63                 SimpleXML soneXml;
64                 try {
65                         soneXml = SimpleXML.fromDocument(document);
66                 } catch (NullPointerException npe1) {
67                         /* for some reason, invalid XML can cause NPEs. */
68                         logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", originalSone), npe1);
69                         return null;
70                 }
71
72                 Integer protocolVersion = null;
73                 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
74                 if (soneProtocolVersion != null) {
75                         protocolVersion = parseInt(soneProtocolVersion, null);
76                 }
77                 if (protocolVersion == null) {
78                         logger.log(Level.INFO, "No protocol version found, assuming 0.");
79                         protocolVersion = 0;
80                 }
81
82                 if (protocolVersion < 0) {
83                         logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
84                         return null;
85                 }
86
87                 /* check for valid versions. */
88                 if (protocolVersion > MAX_PROTOCOL_VERSION) {
89                         logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
90                         return null;
91                 }
92
93                 String soneTime = soneXml.getValue("time", null);
94                 if (soneTime == null) {
95                         /* TODO - mark Sone as bad. */
96                         logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", originalSone));
97                         return null;
98                 }
99                 try {
100                         soneBuilder.lastUpdated(Long.parseLong(soneTime));
101                 } catch (NumberFormatException nfe1) {
102                         /* TODO - mark Sone as bad. */
103                         logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", originalSone, soneTime));
104                         return null;
105                 }
106
107                 SimpleXML clientXml = soneXml.getNode("client");
108                 if (clientXml != null) {
109                         String clientName = clientXml.getValue("name", null);
110                         String clientVersion = clientXml.getValue("version", null);
111                         if ((clientName == null) || (clientVersion == null)) {
112                                 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", originalSone));
113                                 return null;
114                         }
115                         soneBuilder.using(new Client(clientName, clientVersion));
116                 } else {
117                         soneBuilder.using(new Client("Unknown Client", "0.0"));
118                 }
119
120                 SimpleXML profileXml = soneXml.getNode("profile");
121                 if (profileXml == null) {
122                         /* TODO - mark Sone as bad. */
123                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", originalSone));
124                         return null;
125                 }
126
127                 /* parse profile. */
128                 String profileFirstName = profileXml.getValue("first-name", null);
129                 String profileMiddleName = profileXml.getValue("middle-name", null);
130                 String profileLastName = profileXml.getValue("last-name", null);
131                 Integer profileBirthDay = parseInt(profileXml.getValue("birth-day", ""), null);
132                 Integer profileBirthMonth = parseInt(profileXml.getValue("birth-month", ""), null);
133                 Integer profileBirthYear = parseInt(profileXml.getValue("birth-year", ""), null);
134                 Profile profile = new Profile(originalSone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
135                 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
136                 /* avatar is processed after images are loaded. */
137                 String avatarId = profileXml.getValue("avatar", null);
138
139                 /* parse profile fields. */
140                 SimpleXML profileFieldsXml = profileXml.getNode("fields");
141                 if (profileFieldsXml != null) {
142                         for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
143                                 String fieldName = fieldXml.getValue("field-name", null);
144                                 String fieldValue = fieldXml.getValue("field-value", "");
145                                 if (fieldName == null) {
146                                         logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", originalSone, fieldName, fieldValue));
147                                         return null;
148                                 }
149                                 try {
150                                         profile.addField(fieldName.trim()).setValue(fieldValue);
151                                 } catch (IllegalArgumentException iae1) {
152                                         logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
153                                         return null;
154                                 }
155                         }
156                 }
157
158                 /* parse posts. */
159                 SimpleXML postsXml = soneXml.getNode("posts");
160                 if (postsXml == null) {
161                         /* TODO - mark Sone as bad. */
162                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", originalSone));
163                 } else {
164                         Set<Post> posts = new HashSet<Post>();
165                         for (SimpleXML postXml : postsXml.getNodes("post")) {
166                                 String postId = postXml.getValue("id", null);
167                                 String postRecipientId = postXml.getValue("recipient", null);
168                                 String postTime = postXml.getValue("time", null);
169                                 String postText = postXml.getValue("text", null);
170                                 if ((postId == null) || (postTime == null) || (postText == null)) {
171                                         /* TODO - mark Sone as bad. */
172                                         logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", originalSone, postId, postTime, postText));
173                                         return null;
174                                 }
175                                 try {
176                                         PostBuilder postBuilder = core.postBuilder();
177                                         /* TODO - parse time correctly. */
178                                         postBuilder.withId(postId).from(originalSone.getId()).withTime(Long.parseLong(postTime)).withText(postText);
179                                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
180                                                 postBuilder.to(postRecipientId);
181                                         }
182                                         posts.add(postBuilder.build());
183                                 } catch (NumberFormatException nfe1) {
184                                         /* TODO - mark Sone as bad. */
185                                         logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", originalSone, postTime));
186                                         return null;
187                                 }
188                         }
189                         soneBuilder.withPosts(posts);
190                 }
191
192                 /* parse replies. */
193                 SimpleXML repliesXml = soneXml.getNode("replies");
194                 if (repliesXml == null) {
195                         /* TODO - mark Sone as bad. */
196                         logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", originalSone));
197                 } else {
198                         Set<PostReply> replies = new HashSet<PostReply>();
199                         for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
200                                 String replyId = replyXml.getValue("id", null);
201                                 String replyPostId = replyXml.getValue("post-id", null);
202                                 String replyTime = replyXml.getValue("time", null);
203                                 String replyText = replyXml.getValue("text", null);
204                                 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
205                                         /* TODO - mark Sone as bad. */
206                                         logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with missing data! ID: %s, Post: %s, Time: %s, Text: %s", originalSone, replyId, replyPostId, replyTime, replyText));
207                                         return null;
208                                 }
209                                 try {
210                                         PostReplyBuilder postReplyBuilder = core.postReplyBuilder();
211                                         /* TODO - parse time correctly. */
212                                         postReplyBuilder.withId(replyId).from(originalSone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText);
213                                         replies.add(postReplyBuilder.build());
214                                 } catch (NumberFormatException nfe1) {
215                                         /* TODO - mark Sone as bad. */
216                                         logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", originalSone, replyTime));
217                                         return null;
218                                 }
219                         }
220                         soneBuilder.withPostReplies(replies);
221                 }
222                 Sone sone = originalSone.isLocal() ? soneBuilder.buildLocal() : soneBuilder.build();
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.setLikePostIds(likedPostIds);
328                         sone.setLikeReplyIds(likedReplyIds);
329                         for (Album album : topLevelAlbums) {
330                                 sone.getRootAlbum().addAlbum(album);
331                         }
332                 }
333
334                 return sone;
335
336         }
337
338 }