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