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.Sone;
25 import net.pterodactylus.sone.database.PostBuilder;
26 import net.pterodactylus.sone.database.PostReplyBuilder;
27 import net.pterodactylus.sone.database.SoneBuilder;
28 import net.pterodactylus.util.xml.SimpleXML;
29 import net.pterodactylus.util.xml.XML;
31 import org.w3c.dom.Document;
34 * Parses a {@link Sone} from an XML {@link InputStream}.
36 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
38 public class SoneParser {
40 private static final Logger logger = getLogger("Sone.Parser");
41 private static final int MAX_PROTOCOL_VERSION = 0;
42 private final Core core;
44 public SoneParser(Core core) {
48 public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
49 /* TODO - impose a size limit? */
52 /* XML parsing is not thread-safe. */
54 document = XML.transformToDocument(soneInputStream);
56 if (document == null) {
57 /* TODO - mark Sone as bad. */
58 logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
62 SoneBuilder soneBuilder = core.soneBuilder().from(originalSone.getIdentity());
63 if (originalSone.isLocal()) {
64 soneBuilder = soneBuilder.local();
66 Sone sone = soneBuilder.build();
70 soneXml = SimpleXML.fromDocument(document);
71 } catch (NullPointerException npe1) {
72 /* for some reason, invalid XML can cause NPEs. */
73 logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1);
77 Integer protocolVersion = null;
78 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
79 if (soneProtocolVersion != null) {
80 protocolVersion = parseInt(soneProtocolVersion, null);
82 if (protocolVersion == null) {
83 logger.log(Level.INFO, "No protocol version found, assuming 0.");
87 if (protocolVersion < 0) {
88 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
92 /* check for valid versions. */
93 if (protocolVersion > MAX_PROTOCOL_VERSION) {
94 logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
98 String soneTime = soneXml.getValue("time", null);
99 if (soneTime == null) {
100 /* TODO - mark Sone as bad. */
101 logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
105 sone.setTime(Long.parseLong(soneTime));
106 } catch (NumberFormatException nfe1) {
107 /* TODO - mark Sone as bad. */
108 logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
112 SimpleXML clientXml = soneXml.getNode("client");
113 if (clientXml != null) {
114 String clientName = clientXml.getValue("name", null);
115 String clientVersion = clientXml.getValue("version", null);
116 if ((clientName == null) || (clientVersion == null)) {
117 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
120 sone.setClient(new Client(clientName, clientVersion));
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!", sone));
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(sone).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", sone, fieldName, fieldValue));
153 profile.addField(fieldName.trim()).setValue(fieldValue);
154 } catch (DuplicateField df1) {
155 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), df1);
162 SimpleXML postsXml = soneXml.getNode("posts");
163 Set<Post> posts = new HashSet<Post>();
164 if (postsXml == null) {
165 /* TODO - mark Sone as bad. */
166 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
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", sone, postId, postTime, postText));
179 PostBuilder postBuilder = core.postBuilder();
180 /* TODO - parse time correctly. */
181 postBuilder.withId(postId).from(sone.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", sone, postTime));
195 SimpleXML repliesXml = soneXml.getNode("replies");
196 Set<PostReply> replies = new HashSet<PostReply>();
197 if (repliesXml == null) {
198 /* TODO - mark Sone as bad. */
199 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
201 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
202 String replyId = replyXml.getValue("id", null);
203 String replyPostId = replyXml.getValue("post-id", null);
204 String replyTime = replyXml.getValue("time", null);
205 String replyText = replyXml.getValue("text", null);
206 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
207 /* TODO - mark Sone as bad. */
208 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));
212 PostReplyBuilder postReplyBuilder = core.postReplyBuilder();
213 /* TODO - parse time correctly. */
214 postReplyBuilder.withId(replyId).from(sone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText);
215 replies.add(postReplyBuilder.build());
216 } catch (NumberFormatException nfe1) {
217 /* TODO - mark Sone as bad. */
218 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
224 /* parse liked post IDs. */
225 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
226 Set<String> likedPostIds = new HashSet<String>();
227 if (likePostIdsXml == null) {
228 /* TODO - mark Sone as bad. */
229 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
231 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
232 String postId = likedPostIdXml.getValue();
233 likedPostIds.add(postId);
237 /* parse liked reply IDs. */
238 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
239 Set<String> likedReplyIds = new HashSet<String>();
240 if (likeReplyIdsXml == null) {
241 /* TODO - mark Sone as bad. */
242 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
244 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
245 String replyId = likedReplyIdXml.getValue();
246 likedReplyIds.add(replyId);
251 SimpleXML albumsXml = soneXml.getNode("albums");
252 Map<String, Image> allImages = new HashMap<String, Image>();
253 List<Album> topLevelAlbums = new ArrayList<Album>();
254 if (albumsXml != null) {
255 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
256 String id = albumXml.getValue("id", null);
257 String parentId = albumXml.getValue("parent", null);
258 String title = albumXml.getValue("title", null);
259 String description = albumXml.getValue("description", "");
260 String albumImageId = albumXml.getValue("album-image", null);
261 if ((id == null) || (title == null)) {
262 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
266 if (parentId != null) {
267 parent = core.getAlbum(parentId);
268 if (parent == null) {
269 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
273 Album album = core.albumBuilder()
279 .setDescription(description)
281 if (parent != null) {
282 parent.addAlbum(album);
284 topLevelAlbums.add(album);
286 SimpleXML imagesXml = albumXml.getNode("images");
287 if (imagesXml != null) {
288 for (SimpleXML imageXml : imagesXml.getNodes("image")) {
289 String imageId = imageXml.getValue("id", null);
290 String imageCreationTimeString = imageXml.getValue("creation-time", null);
291 String imageKey = imageXml.getValue("key", null);
292 String imageTitle = imageXml.getValue("title", null);
293 String imageDescription = imageXml.getValue("description", "");
294 String imageWidthString = imageXml.getValue("width", null);
295 String imageHeightString = imageXml.getValue("height", null);
296 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
297 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
300 long creationTime = parseLong(imageCreationTimeString, 0L);
301 int imageWidth = parseInt(imageWidthString, 0);
302 int imageHeight = parseInt(imageHeightString, 0);
303 if ((imageWidth < 1) || (imageHeight < 1)) {
304 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
307 Image image = core.imageBuilder().withId(imageId).build().modify().setSone(sone).setKey(imageKey).setCreationTime(creationTime).update();
308 image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
309 image = image.modify().setWidth(imageWidth).setHeight(imageHeight).update();
310 album.addImage(image);
311 allImages.put(imageId, image);
314 album.modify().setAlbumImage(albumImageId).update();
318 /* process avatar. */
319 if (avatarId != null) {
320 profile.setAvatar(allImages.get(avatarId));
323 /* okay, apparently everything was parsed correctly. Now import. */
324 /* atomic setter operation on the Sone. */
325 synchronized (sone) {
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);