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