1 package net.pterodactylus.sone.core;
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;
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;
14 import java.util.logging.Level;
15 import java.util.logging.Logger;
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;
32 import org.w3c.dom.Document;
35 * Parses a {@link Sone} from an XML {@link InputStream}.
37 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
39 public class SoneParser {
41 private static final Logger logger = getLogger(SoneParser.class.getName());
42 private static final int MAX_PROTOCOL_VERSION = 0;
43 private final Core core;
45 public SoneParser(Core core) {
49 public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
50 /* TODO - impose a size limit? */
53 /* XML parsing is not thread-safe. */
55 document = XML.transformToDocument(soneInputStream);
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));
63 SoneBuilder soneBuilder = core.soneBuilder().from(originalSone.getIdentity());
64 if (originalSone.isLocal()) {
65 soneBuilder = soneBuilder.local();
67 Sone sone = soneBuilder.build();
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);
78 Integer protocolVersion = null;
79 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
80 if (soneProtocolVersion != null) {
81 protocolVersion = parseInt(soneProtocolVersion, null);
83 if (protocolVersion == null) {
84 logger.log(Level.INFO, "No protocol version found, assuming 0.");
88 if (protocolVersion < 0) {
89 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
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));
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));
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));
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));
121 sone.setClient(new Client(clientName, clientVersion));
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));
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);
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));
154 profile.addField(fieldName.trim()).setValue(fieldValue);
155 } catch (EmptyFieldName efn1) {
156 logger.log(Level.WARNING, "Empty field name!", efn1);
158 } catch (DuplicateField df1) {
159 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), df1);
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));
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));
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);
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));
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));
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));
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));
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));
235 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
236 String postId = likedPostIdXml.getValue();
237 likedPostIds.add(postId);
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));
248 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
249 String replyId = likedReplyIdXml.getValue();
250 likedReplyIds.add(replyId);
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));
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));
276 Album album = core.albumBuilder()
282 .setDescription(description)
284 if (parent != null) {
285 parent.addAlbum(album);
287 topLevelAlbums.add(album);
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));
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));
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);
320 /* process avatar. */
321 if (avatarId != null) {
322 profile.setAvatar(allImages.get(avatarId));
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);