1 package net.pterodactylus.sone.core;
3 import static java.util.logging.Logger.getLogger;
5 import java.io.InputStream;
6 import java.util.ArrayList;
7 import java.util.HashMap;
8 import java.util.HashSet;
12 import java.util.logging.Level;
13 import java.util.logging.Logger;
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;
29 import org.w3c.dom.Document;
32 * Parses a {@link Sone} from an XML {@link InputStream}.
34 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
36 public class SoneParser {
38 private static final Logger logger = getLogger("Sone.Parser");
39 private static final int MAX_PROTOCOL_VERSION = 0;
40 private final Core core;
42 public SoneParser(Core core) {
46 public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
47 /* TODO - impose a size limit? */
50 /* XML parsing is not thread-safe. */
52 document = XML.transformToDocument(soneInputStream);
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));
60 SoneBuilder soneBuilder = core.soneBuilder().from(originalSone.getIdentity());
61 if (originalSone.isLocal()) {
62 soneBuilder = soneBuilder.local();
64 Sone sone = soneBuilder.build();
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);
75 Integer protocolVersion = null;
76 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
77 if (soneProtocolVersion != null) {
78 protocolVersion = Numbers.safeParseInteger(soneProtocolVersion);
80 if (protocolVersion == null) {
81 logger.log(Level.INFO, "No protocol version found, assuming 0.");
85 if (protocolVersion < 0) {
86 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
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));
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));
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));
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));
118 sone.setClient(new Client(clientName, clientVersion));
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));
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);
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));
151 profile.addField(fieldName.trim()).setValue(fieldValue);
152 } catch (IllegalArgumentException iae1) {
153 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
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));
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));
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);
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));
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));
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));
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));
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));
229 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
230 String postId = likedPostIdXml.getValue();
231 likedPostIds.add(postId);
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));
242 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
243 String replyId = likedReplyIdXml.getValue();
244 likedReplyIds.add(replyId);
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));
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));
271 Album album = core.albumBuilder()
277 .setDescription(description)
279 if (parent != null) {
280 parent.addAlbum(album);
282 topLevelAlbums.add(album);
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));
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));
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);
312 album.modify().setAlbumImage(albumImageId).update();
316 /* process avatar. */
317 if (avatarId != null) {
318 profile.setAvatar(allImages.get(avatarId));
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);