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 com.google.common.base.Optional;
33 import org.w3c.dom.Document;
36 * Parses a {@link Sone} from an XML {@link InputStream}.
38 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
40 public class SoneParser {
42 private static final Logger logger = getLogger(SoneParser.class.getName());
43 private static final int MAX_PROTOCOL_VERSION = 0;
44 private final Core core;
46 public SoneParser(Core core) {
50 public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
51 /* TODO - impose a size limit? */
54 /* XML parsing is not thread-safe. */
56 document = XML.transformToDocument(soneInputStream);
58 if (document == null) {
59 /* TODO - mark Sone as bad. */
60 logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
64 SoneBuilder soneBuilder = core.soneBuilder().from(originalSone.getIdentity());
65 if (originalSone.isLocal()) {
66 soneBuilder = soneBuilder.local();
68 Sone sone = soneBuilder.build();
72 soneXml = SimpleXML.fromDocument(document);
73 } catch (NullPointerException npe1) {
74 /* for some reason, invalid XML can cause NPEs. */
75 logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1);
79 Integer protocolVersion = null;
80 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
81 if (soneProtocolVersion != null) {
82 protocolVersion = parseInt(soneProtocolVersion, null);
84 if (protocolVersion == null) {
85 logger.log(Level.INFO, "No protocol version found, assuming 0.");
89 if (protocolVersion < 0) {
90 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
94 /* check for valid versions. */
95 if (protocolVersion > MAX_PROTOCOL_VERSION) {
96 logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
100 String soneTime = soneXml.getValue("time", null);
101 if (soneTime == null) {
102 /* TODO - mark Sone as bad. */
103 logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
107 sone.setTime(Long.parseLong(soneTime));
108 } catch (NumberFormatException nfe1) {
109 /* TODO - mark Sone as bad. */
110 logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
114 SimpleXML clientXml = soneXml.getNode("client");
115 if (clientXml != null) {
116 String clientName = clientXml.getValue("name", null);
117 String clientVersion = clientXml.getValue("version", null);
118 if ((clientName == null) || (clientVersion == null)) {
119 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
122 sone.setClient(new Client(clientName, clientVersion));
125 SimpleXML profileXml = soneXml.getNode("profile");
126 if (profileXml == null) {
127 /* TODO - mark Sone as bad. */
128 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
133 String profileFirstName = profileXml.getValue("first-name", null);
134 String profileMiddleName = profileXml.getValue("middle-name", null);
135 String profileLastName = profileXml.getValue("last-name", null);
136 Integer profileBirthDay = parseInt(profileXml.getValue("birth-day", ""), null);
137 Integer profileBirthMonth = parseInt(profileXml.getValue("birth-month", ""), null);
138 Integer profileBirthYear = parseInt(profileXml.getValue("birth-year", ""), null);
139 Profile profile = new Profile(sone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
140 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
141 /* avatar is processed after images are loaded. */
142 String avatarId = profileXml.getValue("avatar", null);
144 /* parse profile fields. */
145 SimpleXML profileFieldsXml = profileXml.getNode("fields");
146 if (profileFieldsXml != null) {
147 for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
148 String fieldName = fieldXml.getValue("field-name", null);
149 String fieldValue = fieldXml.getValue("field-value", "");
150 if (fieldName == null) {
151 logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
155 profile.addField(fieldName.trim()).setValue(fieldValue);
156 } catch (EmptyFieldName efn1) {
157 logger.log(Level.WARNING, "Empty field name!", efn1);
159 } catch (DuplicateField df1) {
160 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), df1);
167 SimpleXML postsXml = soneXml.getNode("posts");
168 Set<Post> posts = new HashSet<Post>();
169 if (postsXml == null) {
170 /* TODO - mark Sone as bad. */
171 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
173 for (SimpleXML postXml : postsXml.getNodes("post")) {
174 String postId = postXml.getValue("id", null);
175 String postRecipientId = postXml.getValue("recipient", null);
176 String postTime = postXml.getValue("time", null);
177 String postText = postXml.getValue("text", null);
178 if ((postId == null) || (postTime == null) || (postText == null)) {
179 /* TODO - mark Sone as bad. */
180 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
184 PostBuilder postBuilder = core.postBuilder();
185 /* TODO - parse time correctly. */
186 postBuilder.withId(postId).from(sone.getId()).withTime(Long.parseLong(postTime)).withText(postText);
187 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
188 postBuilder.to(postRecipientId);
190 posts.add(postBuilder.build());
191 } catch (NumberFormatException nfe1) {
192 /* TODO - mark Sone as bad. */
193 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
200 SimpleXML repliesXml = soneXml.getNode("replies");
201 Set<PostReply> replies = new HashSet<PostReply>();
202 if (repliesXml == null) {
203 /* TODO - mark Sone as bad. */
204 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
206 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
207 String replyId = replyXml.getValue("id", null);
208 String replyPostId = replyXml.getValue("post-id", null);
209 String replyTime = replyXml.getValue("time", null);
210 String replyText = replyXml.getValue("text", null);
211 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
212 /* TODO - mark Sone as bad. */
213 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));
217 PostReplyBuilder postReplyBuilder = core.postReplyBuilder();
218 /* TODO - parse time correctly. */
219 postReplyBuilder.withId(replyId).from(sone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText);
220 replies.add(postReplyBuilder.build());
221 } catch (NumberFormatException nfe1) {
222 /* TODO - mark Sone as bad. */
223 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
229 /* parse liked post IDs. */
230 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
231 Set<String> likedPostIds = new HashSet<String>();
232 if (likePostIdsXml == null) {
233 /* TODO - mark Sone as bad. */
234 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
236 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
237 String postId = likedPostIdXml.getValue();
238 likedPostIds.add(postId);
242 /* parse liked reply IDs. */
243 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
244 Set<String> likedReplyIds = new HashSet<String>();
245 if (likeReplyIdsXml == null) {
246 /* TODO - mark Sone as bad. */
247 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
249 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
250 String replyId = likedReplyIdXml.getValue();
251 likedReplyIds.add(replyId);
256 SimpleXML albumsXml = soneXml.getNode("albums");
257 Map<String, Image> allImages = new HashMap<String, Image>();
258 List<Album> topLevelAlbums = new ArrayList<Album>();
259 if (albumsXml != null) {
260 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
261 String id = albumXml.getValue("id", null);
262 String parentId = albumXml.getValue("parent", null);
263 String title = albumXml.getValue("title", null);
264 String description = albumXml.getValue("description", "");
265 String albumImageId = albumXml.getValue("album-image", null);
266 if ((id == null) || (title == null)) {
267 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
270 Optional<Album> parent = Optional.absent();
271 if (parentId != null) {
272 parent = core.getAlbum(parentId);
273 if (!parent.isPresent()) {
274 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
278 Album album = core.albumBuilder()
284 .setDescription(description)
286 if (parent.isPresent()) {
287 parent.get().addAlbum(album);
289 topLevelAlbums.add(album);
291 SimpleXML imagesXml = albumXml.getNode("images");
292 if (imagesXml != null) {
293 for (SimpleXML imageXml : imagesXml.getNodes("image")) {
294 String imageId = imageXml.getValue("id", null);
295 String imageCreationTimeString = imageXml.getValue("creation-time", null);
296 String imageKey = imageXml.getValue("key", null);
297 String imageTitle = imageXml.getValue("title", null);
298 String imageDescription = imageXml.getValue("description", "");
299 String imageWidthString = imageXml.getValue("width", null);
300 String imageHeightString = imageXml.getValue("height", null);
301 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
302 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
305 long creationTime = parseLong(imageCreationTimeString, 0L);
306 int imageWidth = parseInt(imageWidthString, 0);
307 int imageHeight = parseInt(imageHeightString, 0);
308 if ((imageWidth < 1) || (imageHeight < 1)) {
309 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
312 Image image = core.imageBuilder().withId(imageId).build().modify().setSone(sone).setKey(imageKey).setCreationTime(creationTime).update();
313 image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
314 image = image.modify().setWidth(imageWidth).setHeight(imageHeight).update();
315 album.addImage(image);
316 allImages.put(imageId, image);
319 album.modify().setAlbumImage(albumImageId).update();
323 /* process avatar. */
324 if (avatarId != null) {
325 profile.setAvatar(allImages.get(avatarId));
328 /* okay, apparently everything was parsed correctly. Now import. */
329 sone.setProfile(profile);
330 sone.setPosts(posts);
331 sone.setReplies(replies);
332 sone.setLikePostIds(likedPostIds);
333 sone.setLikeReplyIds(likedReplyIds);
334 for (Album album : topLevelAlbums) {
335 sone.getRootAlbum().addAlbum(album);