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