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