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