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.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;
30 import org.w3c.dom.Document;
33 * Parses a {@link Sone} from an XML {@link InputStream}.
35 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
37 public class SoneParser {
39 private static final Logger logger = getLogger("Sone.Parser");
40 private static final int MAX_PROTOCOL_VERSION = 0;
41 private final Core core;
43 public SoneParser(Core core) {
47 public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
48 /* TODO - impose a size limit? */
51 /* XML parsing is not thread-safe. */
53 document = XML.transformToDocument(soneInputStream);
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));
61 SoneBuilder soneBuilder = core.soneBuilder().from(originalSone.getIdentity());
62 if (originalSone.isLocal()) {
63 soneBuilder = soneBuilder.local();
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!", originalSone), npe1);
75 Integer protocolVersion = null;
76 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
77 if (soneProtocolVersion != null) {
78 protocolVersion = parseInt(soneProtocolVersion, null);
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!", originalSone));
103 soneBuilder.lastUpdated(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", originalSone, 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!", originalSone));
118 soneBuilder.using(new Client(clientName, clientVersion));
120 soneBuilder.using(new Client("Unknown Client", "0.0"));
123 SimpleXML profileXml = soneXml.getNode("profile");
124 if (profileXml == null) {
125 /* TODO - mark Sone as bad. */
126 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", originalSone));
131 String profileFirstName = profileXml.getValue("first-name", null);
132 String profileMiddleName = profileXml.getValue("middle-name", null);
133 String profileLastName = profileXml.getValue("last-name", null);
134 Integer profileBirthDay = parseInt(profileXml.getValue("birth-day", ""), null);
135 Integer profileBirthMonth = parseInt(profileXml.getValue("birth-month", ""), null);
136 Integer profileBirthYear = parseInt(profileXml.getValue("birth-year", ""), null);
137 Profile profile = new Profile(originalSone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
138 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
139 /* avatar is processed after images are loaded. */
140 String avatarId = profileXml.getValue("avatar", null);
142 /* parse profile fields. */
143 SimpleXML profileFieldsXml = profileXml.getNode("fields");
144 if (profileFieldsXml != null) {
145 for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
146 String fieldName = fieldXml.getValue("field-name", null);
147 String fieldValue = fieldXml.getValue("field-value", "");
148 if (fieldName == null) {
149 logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", originalSone, fieldName, fieldValue));
153 profile.addField(fieldName.trim()).setValue(fieldValue);
154 } catch (IllegalArgumentException iae1) {
155 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
162 SimpleXML postsXml = soneXml.getNode("posts");
163 if (postsXml == null) {
164 /* TODO - mark Sone as bad. */
165 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", originalSone));
167 Set<Post> posts = new HashSet<Post>();
168 for (SimpleXML postXml : postsXml.getNodes("post")) {
169 String postId = postXml.getValue("id", null);
170 String postRecipientId = postXml.getValue("recipient", null);
171 String postTime = postXml.getValue("time", null);
172 String postText = postXml.getValue("text", null);
173 if ((postId == null) || (postTime == null) || (postText == null)) {
174 /* TODO - mark Sone as bad. */
175 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", originalSone, postId, postTime, postText));
179 PostBuilder postBuilder = core.postBuilder();
180 /* TODO - parse time correctly. */
181 postBuilder.withId(postId).from(originalSone.getId()).withTime(Long.parseLong(postTime)).withText(postText);
182 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
183 postBuilder.to(postRecipientId);
185 posts.add(postBuilder.build());
186 } catch (NumberFormatException nfe1) {
187 /* TODO - mark Sone as bad. */
188 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", originalSone, postTime));
192 soneBuilder.withPosts(posts);
196 SimpleXML repliesXml = soneXml.getNode("replies");
197 if (repliesXml == null) {
198 /* TODO - mark Sone as bad. */
199 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", originalSone));
201 Set<PostReply> replies = new HashSet<PostReply>();
202 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
203 String replyId = replyXml.getValue("id", null);
204 String replyPostId = replyXml.getValue("post-id", null);
205 String replyTime = replyXml.getValue("time", null);
206 String replyText = replyXml.getValue("text", null);
207 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
208 /* TODO - mark Sone as bad. */
209 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with missing data! ID: %s, Post: %s, Time: %s, Text: %s", originalSone, replyId, replyPostId, replyTime, replyText));
213 PostReplyBuilder postReplyBuilder = core.postReplyBuilder();
214 /* TODO - parse time correctly. */
215 postReplyBuilder.withId(replyId).from(originalSone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText);
216 replies.add(postReplyBuilder.build());
217 } catch (NumberFormatException nfe1) {
218 /* TODO - mark Sone as bad. */
219 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", originalSone, replyTime));
223 soneBuilder.withPostReplies(replies);
225 Sone sone = soneBuilder.build();
227 /* parse liked post IDs. */
228 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
229 Set<String> likedPostIds = new HashSet<String>();
230 if (likePostIdsXml == null) {
231 /* TODO - mark Sone as bad. */
232 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
234 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
235 String postId = likedPostIdXml.getValue();
236 likedPostIds.add(postId);
240 /* parse liked reply IDs. */
241 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
242 Set<String> likedReplyIds = new HashSet<String>();
243 if (likeReplyIdsXml == null) {
244 /* TODO - mark Sone as bad. */
245 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
247 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
248 String replyId = likedReplyIdXml.getValue();
249 likedReplyIds.add(replyId);
254 SimpleXML albumsXml = soneXml.getNode("albums");
255 Map<String, Image> allImages = new HashMap<String, Image>();
256 List<Album> topLevelAlbums = new ArrayList<Album>();
257 if (albumsXml != null) {
258 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
259 String id = albumXml.getValue("id", null);
260 String parentId = albumXml.getValue("parent", null);
261 String title = albumXml.getValue("title", null);
262 String description = albumXml.getValue("description", "");
263 String albumImageId = albumXml.getValue("album-image", null);
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);
317 album.modify().setAlbumImage(albumImageId).update();
321 /* process avatar. */
322 if (avatarId != null) {
323 profile.setAvatar(allImages.get(avatarId));
326 /* okay, apparently everything was parsed correctly. Now import. */
327 /* atomic setter operation on the Sone. */
328 synchronized (sone) {
329 sone.setProfile(profile);
330 sone.setLikePostIds(likedPostIds);
331 sone.setLikeReplyIds(likedReplyIds);
332 for (Album album : topLevelAlbums) {
333 sone.getRootAlbum().addAlbum(album);