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 javax.inject.Inject;
19 import net.pterodactylus.sone.data.Album;
20 import net.pterodactylus.sone.data.Client;
21 import net.pterodactylus.sone.data.Image;
22 import net.pterodactylus.sone.data.Post;
23 import net.pterodactylus.sone.data.PostReply;
24 import net.pterodactylus.sone.data.Profile;
25 import net.pterodactylus.sone.data.Profile.DuplicateField;
26 import net.pterodactylus.sone.data.Profile.EmptyFieldName;
27 import net.pterodactylus.sone.data.Sone;
28 import net.pterodactylus.sone.database.Database;
29 import net.pterodactylus.sone.database.PostBuilder;
30 import net.pterodactylus.sone.database.PostReplyBuilder;
31 import net.pterodactylus.sone.database.SoneBuilder;
32 import net.pterodactylus.util.xml.SimpleXML;
33 import net.pterodactylus.util.xml.XML;
35 import org.w3c.dom.Document;
38 * Parses a {@link Sone} from an XML {@link InputStream}.
40 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
42 public class SoneParser {
44 private static final Logger logger = getLogger(SoneParser.class.getName());
45 private static final int MAX_PROTOCOL_VERSION = 0;
46 private final Database database;
49 public SoneParser(Database database) {
50 this.database = database;
53 public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
54 /* TODO - impose a size limit? */
57 /* XML parsing is not thread-safe. */
59 document = XML.transformToDocument(soneInputStream);
61 if (document == null) {
62 /* TODO - mark Sone as bad. */
63 logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
67 SoneBuilder soneBuilder = database.newSoneBuilder().from(originalSone.getIdentity());
68 if (originalSone.isLocal()) {
69 soneBuilder = soneBuilder.local();
71 Sone sone = soneBuilder.build();
75 soneXml = SimpleXML.fromDocument(document);
76 } catch (NullPointerException npe1) {
77 /* for some reason, invalid XML can cause NPEs. */
78 logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1);
82 Integer protocolVersion = null;
83 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
84 if (soneProtocolVersion != null) {
85 protocolVersion = parseInt(soneProtocolVersion, null);
87 if (protocolVersion == null) {
88 logger.log(Level.INFO, "No protocol version found, assuming 0.");
92 if (protocolVersion < 0) {
93 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
97 /* check for valid versions. */
98 if (protocolVersion > MAX_PROTOCOL_VERSION) {
99 logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
103 String soneTime = soneXml.getValue("time", null);
104 if (soneTime == null) {
105 /* TODO - mark Sone as bad. */
106 logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
110 sone.setTime(Long.parseLong(soneTime));
111 } catch (NumberFormatException nfe1) {
112 /* TODO - mark Sone as bad. */
113 logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
117 SimpleXML clientXml = soneXml.getNode("client");
118 if (clientXml != null) {
119 String clientName = clientXml.getValue("name", null);
120 String clientVersion = clientXml.getValue("version", null);
121 if ((clientName == null) || (clientVersion == null)) {
122 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
125 sone.setClient(new Client(clientName, clientVersion));
128 SimpleXML profileXml = soneXml.getNode("profile");
129 if (profileXml == null) {
130 /* TODO - mark Sone as bad. */
131 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
136 String profileFirstName = profileXml.getValue("first-name", null);
137 String profileMiddleName = profileXml.getValue("middle-name", null);
138 String profileLastName = profileXml.getValue("last-name", null);
139 Integer profileBirthDay = parseInt(profileXml.getValue("birth-day", ""), null);
140 Integer profileBirthMonth = parseInt(profileXml.getValue("birth-month", ""), null);
141 Integer profileBirthYear = parseInt(profileXml.getValue("birth-year", ""), null);
142 Profile profile = new Profile(sone).setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
143 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
144 /* avatar is processed after images are loaded. */
145 String avatarId = profileXml.getValue("avatar", null);
147 /* parse profile fields. */
148 SimpleXML profileFieldsXml = profileXml.getNode("fields");
149 if (profileFieldsXml != null) {
150 for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
151 String fieldName = fieldXml.getValue("field-name", null);
152 String fieldValue = fieldXml.getValue("field-value", "");
153 if (fieldName == null) {
154 logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
158 profile.addField(fieldName.trim()).setValue(fieldValue);
159 } catch (EmptyFieldName efn1) {
160 logger.log(Level.WARNING, "Empty field name!", efn1);
162 } catch (DuplicateField df1) {
163 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), df1);
170 SimpleXML postsXml = soneXml.getNode("posts");
171 Set<Post> posts = new HashSet<Post>();
172 if (postsXml == null) {
173 /* TODO - mark Sone as bad. */
174 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
176 for (SimpleXML postXml : postsXml.getNodes("post")) {
177 String postId = postXml.getValue("id", null);
178 String postRecipientId = postXml.getValue("recipient", null);
179 String postTime = postXml.getValue("time", null);
180 String postText = postXml.getValue("text", null);
181 if ((postId == null) || (postTime == null) || (postText == null)) {
182 /* TODO - mark Sone as bad. */
183 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
187 PostBuilder postBuilder = database.newPostBuilder();
188 /* TODO - parse time correctly. */
189 postBuilder.withId(postId).from(sone.getId()).withTime(Long.parseLong(postTime)).withText(postText);
190 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
191 postBuilder.to(postRecipientId);
193 posts.add(postBuilder.build());
194 } catch (NumberFormatException nfe1) {
195 /* TODO - mark Sone as bad. */
196 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
203 SimpleXML repliesXml = soneXml.getNode("replies");
204 Set<PostReply> replies = new HashSet<PostReply>();
205 if (repliesXml == null) {
206 /* TODO - mark Sone as bad. */
207 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
209 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
210 String replyId = replyXml.getValue("id", null);
211 String replyPostId = replyXml.getValue("post-id", null);
212 String replyTime = replyXml.getValue("time", null);
213 String replyText = replyXml.getValue("text", null);
214 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
215 /* TODO - mark Sone as bad. */
216 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));
220 PostReplyBuilder postReplyBuilder = database.newPostReplyBuilder();
221 /* TODO - parse time correctly. */
222 postReplyBuilder.withId(replyId).from(sone.getId()).to(replyPostId).withTime(Long.parseLong(replyTime)).withText(replyText);
223 replies.add(postReplyBuilder.build());
224 } catch (NumberFormatException nfe1) {
225 /* TODO - mark Sone as bad. */
226 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
232 /* parse liked post IDs. */
233 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
234 Set<String> likedPostIds = new HashSet<String>();
235 if (likePostIdsXml == null) {
236 /* TODO - mark Sone as bad. */
237 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
239 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
240 String postId = likedPostIdXml.getValue();
241 likedPostIds.add(postId);
245 /* parse liked reply IDs. */
246 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
247 Set<String> likedReplyIds = new HashSet<String>();
248 if (likeReplyIdsXml == null) {
249 /* TODO - mark Sone as bad. */
250 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
252 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
253 String replyId = likedReplyIdXml.getValue();
254 likedReplyIds.add(replyId);
259 SimpleXML albumsXml = soneXml.getNode("albums");
260 Map<String, Image> allImages = new HashMap<String, Image>();
261 List<Album> topLevelAlbums = new ArrayList<Album>();
262 if (albumsXml != null) {
263 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
264 String id = albumXml.getValue("id", null);
265 String parentId = albumXml.getValue("parent", null);
266 String title = albumXml.getValue("title", null);
267 String description = albumXml.getValue("description", "");
268 if ((id == null) || (title == null)) {
269 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
273 if (parentId != null) {
274 parent = database.getAlbum(parentId);
275 if (parent == null) {
276 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
280 Album album = database.newAlbumBuilder()
286 .setDescription(description)
288 if (parent != null) {
289 parent.addAlbum(album);
291 topLevelAlbums.add(album);
293 SimpleXML imagesXml = albumXml.getNode("images");
294 if (imagesXml != null) {
295 for (SimpleXML imageXml : imagesXml.getNodes("image")) {
296 String imageId = imageXml.getValue("id", null);
297 String imageCreationTimeString = imageXml.getValue("creation-time", null);
298 String imageKey = imageXml.getValue("key", null);
299 String imageTitle = imageXml.getValue("title", null);
300 String imageDescription = imageXml.getValue("description", "");
301 String imageWidthString = imageXml.getValue("width", null);
302 String imageHeightString = imageXml.getValue("height", null);
303 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
304 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
307 long creationTime = parseLong(imageCreationTimeString, 0L);
308 int imageWidth = parseInt(imageWidthString, 0);
309 int imageHeight = parseInt(imageHeightString, 0);
310 if ((imageWidth < 1) || (imageHeight < 1)) {
311 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
314 Image image = database.newImageBuilder().withId(imageId).build().modify().setSone(sone).setKey(imageKey).setCreationTime(creationTime).update();
315 image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
316 image = image.modify().setWidth(imageWidth).setHeight(imageHeight).update();
317 album.addImage(image);
318 allImages.put(imageId, image);
324 /* process avatar. */
325 if (avatarId != null) {
326 profile.setAvatar(allImages.get(avatarId));
329 /* okay, apparently everything was parsed correctly. Now import. */
330 sone.setProfile(profile);
331 sone.setPosts(posts);
332 sone.setReplies(replies);
333 sone.setLikePostIds(likedPostIds);
334 sone.setLikeReplyIds(likedReplyIds);
335 for (Album album : topLevelAlbums) {
336 sone.getRootAlbum().addAlbum(album);