2 * Sone - SoneParser.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.io.InputStream;
21 import java.net.MalformedURLException;
22 import java.util.HashSet;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
28 import net.pterodactylus.sone.data.Album;
29 import net.pterodactylus.sone.data.Client;
30 import net.pterodactylus.sone.data.Image;
31 import net.pterodactylus.sone.data.Post;
32 import net.pterodactylus.sone.data.PostReply;
33 import net.pterodactylus.sone.data.Profile;
34 import net.pterodactylus.sone.data.Profile.Name;
35 import net.pterodactylus.sone.data.Sone;
36 import net.pterodactylus.sone.data.impl.DefaultSone;
37 import net.pterodactylus.sone.database.ImageBuilder.ImageCreated;
38 import net.pterodactylus.sone.database.PostBuilder;
39 import net.pterodactylus.sone.database.PostBuilder.PostCreated;
40 import net.pterodactylus.sone.database.PostReplyBuilder;
41 import net.pterodactylus.sone.database.PostReplyBuilder.PostReplyCreated;
42 import net.pterodactylus.sone.database.memory.MemoryDatabase;
43 import net.pterodactylus.util.number.Numbers;
44 import net.pterodactylus.util.xml.SimpleXML;
45 import net.pterodactylus.util.xml.XML;
47 import freenet.keys.FreenetURI;
49 import com.google.common.base.Optional;
50 import com.google.common.collect.Maps;
51 import org.w3c.dom.Document;
54 * Parses the inserted XML representation of a {@link Sone} into a Sone.
56 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
58 public class SoneParser {
60 private static final Logger logger = Logger.getLogger(SoneParser.class.getName());
61 private static final int MAX_PROTOCOL_VERSION = 0;
62 private final Core core;
64 public SoneParser(Core core) {
69 * Parses a Sone from the given input stream and creates a new Sone from the
74 * @param soneInputStream
75 * The input stream to parse the Sone from
76 * @return The parsed Sone
77 * @throws SoneException
78 * if a parse error occurs, or the protocol is invalid
80 public Sone parseSone(Sone originalSone, InputStream soneInputStream) throws SoneException {
81 /* TODO - impose a size limit? */
84 /* XML parsing is not thread-safe. */
86 document = XML.transformToDocument(soneInputStream);
88 if (document == null) {
89 /* TODO - mark Sone as bad. */
90 logger.log(Level.WARNING, String.format("Could not parse XML for Sone %s!", originalSone));
94 Sone sone = new DefaultSone(new MemoryDatabase(null), originalSone.getId(), originalSone.isLocal()).setIdentity(originalSone.getIdentity());
98 soneXml = SimpleXML.fromDocument(document);
99 } catch (NullPointerException npe1) {
100 /* for some reason, invalid XML can cause NPEs. */
101 logger.log(Level.WARNING, String.format("XML for Sone %s can not be parsed!", sone), npe1);
105 Integer protocolVersion = null;
106 String soneProtocolVersion = soneXml.getValue("protocol-version", null);
107 if (soneProtocolVersion != null) {
108 protocolVersion = Numbers.safeParseInteger(soneProtocolVersion);
110 if (protocolVersion == null) {
111 logger.log(Level.INFO, "No protocol version found, assuming 0.");
115 if (protocolVersion < 0) {
116 logger.log(Level.WARNING, String.format("Invalid protocol version: %d! Not parsing Sone.", protocolVersion));
120 /* check for valid versions. */
121 if (protocolVersion > MAX_PROTOCOL_VERSION) {
122 logger.log(Level.WARNING, String.format("Unknown protocol version: %d! Not parsing Sone.", protocolVersion));
126 String soneTime = soneXml.getValue("time", null);
127 if (soneTime == null) {
128 /* TODO - mark Sone as bad. */
129 logger.log(Level.WARNING, String.format("Downloaded time for Sone %s was null!", sone));
133 sone.setTime(Long.parseLong(soneTime));
134 } catch (NumberFormatException nfe1) {
135 /* TODO - mark Sone as bad. */
136 logger.log(Level.WARNING, String.format("Downloaded Sone %s with invalid time: %s", sone, soneTime));
140 SimpleXML clientXml = soneXml.getNode("client");
141 if (clientXml != null) {
142 String clientName = clientXml.getValue("name", null);
143 String clientVersion = clientXml.getValue("version", null);
144 if ((clientName == null) || (clientVersion == null)) {
145 logger.log(Level.WARNING, String.format("Download Sone %s with client XML but missing name or version!", sone));
148 sone.setClient(new Client(clientName, clientVersion));
151 String soneRequestUri = soneXml.getValue("request-uri", null);
152 if (soneRequestUri != null) {
154 sone.setRequestUri(new FreenetURI(soneRequestUri));
155 } catch (MalformedURLException mue1) {
156 /* TODO - mark Sone as bad. */
157 logger.log(Level.WARNING, String.format("Downloaded Sone %s has invalid request URI: %s", sone, soneRequestUri), mue1);
162 if (originalSone.getInsertUri() != null) {
163 sone.setInsertUri(originalSone.getInsertUri());
166 SimpleXML profileXml = soneXml.getNode("profile");
167 if (profileXml == null) {
168 /* TODO - mark Sone as bad. */
169 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no profile!", sone));
174 String profileFirstName = profileXml.getValue("first-name", null);
175 String profileMiddleName = profileXml.getValue("middle-name", null);
176 String profileLastName = profileXml.getValue("last-name", null);
177 Integer profileBirthDay = Numbers.safeParseInteger(profileXml.getValue("birth-day", null));
178 Integer profileBirthMonth = Numbers.safeParseInteger(profileXml.getValue("birth-month", null));
179 Integer profileBirthYear = Numbers.safeParseInteger(profileXml.getValue("birth-year", null));
180 Profile profile = new Profile(sone).modify().setName(new Name(profileFirstName, profileMiddleName, profileLastName)).update();
181 profile.setBirthDay(profileBirthDay).setBirthMonth(profileBirthMonth).setBirthYear(profileBirthYear);
182 /* avatar is processed after images are loaded. */
183 String avatarId = profileXml.getValue("avatar", null);
185 /* parse profile fields. */
186 SimpleXML profileFieldsXml = profileXml.getNode("fields");
187 if (profileFieldsXml != null) {
188 for (SimpleXML fieldXml : profileFieldsXml.getNodes("field")) {
189 String fieldName = fieldXml.getValue("field-name", null);
190 String fieldValue = fieldXml.getValue("field-value", "");
191 if (fieldName == null) {
192 logger.log(Level.WARNING, String.format("Downloaded profile field for Sone %s with missing data! Name: %s, Value: %s", sone, fieldName, fieldValue));
196 profile.addField(fieldName).setValue(fieldValue);
197 } catch (IllegalArgumentException iae1) {
198 logger.log(Level.WARNING, String.format("Duplicate field: %s", fieldName), iae1);
205 SimpleXML postsXml = soneXml.getNode("posts");
206 Set<Post> posts = new HashSet<Post>();
207 if (postsXml == null) {
208 /* TODO - mark Sone as bad. */
209 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no posts!", sone));
211 for (SimpleXML postXml : postsXml.getNodes("post")) {
212 String postId = postXml.getValue("id", null);
213 String postRecipientId = postXml.getValue("recipient", null);
214 String postTime = postXml.getValue("time", null);
215 String postText = postXml.getValue("text", null);
216 if ((postId == null) || (postTime == null) || (postText == null)) {
217 /* TODO - mark Sone as bad. */
218 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", sone, postId, postTime, postText));
222 PostBuilder postBuilder = sone.newPostBuilder();
223 /* TODO - parse time correctly. */
224 postBuilder.withId(postId).withTime(Long.parseLong(postTime)).withText(postText);
225 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
226 postBuilder.to(Optional.of(postRecipientId));
228 posts.add(postBuilder.build(Optional.<PostCreated>absent()));
229 } catch (NumberFormatException nfe1) {
230 /* TODO - mark Sone as bad. */
231 logger.log(Level.WARNING, String.format("Downloaded post for Sone %s with invalid time: %s", sone, postTime));
238 SimpleXML repliesXml = soneXml.getNode("replies");
239 Set<PostReply> replies = new HashSet<PostReply>();
240 if (repliesXml == null) {
241 /* TODO - mark Sone as bad. */
242 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no replies!", sone));
244 for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
245 String replyId = replyXml.getValue("id", null);
246 String replyPostId = replyXml.getValue("post-id", null);
247 String replyTime = replyXml.getValue("time", null);
248 String replyText = replyXml.getValue("text", null);
249 if ((replyId == null) || (replyPostId == null) || (replyTime == null) || (replyText == null)) {
250 /* TODO - mark Sone as bad. */
251 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));
255 /* TODO - parse time correctly. */
256 PostReplyBuilder postReplyBuilder = sone.newPostReplyBuilder(replyPostId).withId(replyId).withTime(Long.parseLong(replyTime)).withText(replyText);
257 replies.add(postReplyBuilder.build(Optional.<PostReplyCreated>absent()));
258 } catch (NumberFormatException nfe1) {
259 /* TODO - mark Sone as bad. */
260 logger.log(Level.WARNING, String.format("Downloaded reply for Sone %s with invalid time: %s", sone, replyTime));
266 /* parse liked post IDs. */
267 SimpleXML likePostIdsXml = soneXml.getNode("post-likes");
268 Set<String> likedPostIds = new HashSet<String>();
269 if (likePostIdsXml == null) {
270 /* TODO - mark Sone as bad. */
271 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no post likes!", sone));
273 for (SimpleXML likedPostIdXml : likePostIdsXml.getNodes("post-like")) {
274 String postId = likedPostIdXml.getValue();
275 likedPostIds.add(postId);
279 /* parse liked reply IDs. */
280 SimpleXML likeReplyIdsXml = soneXml.getNode("reply-likes");
281 Set<String> likedReplyIds = new HashSet<String>();
282 if (likeReplyIdsXml == null) {
283 /* TODO - mark Sone as bad. */
284 logger.log(Level.WARNING, String.format("Downloaded Sone %s has no reply likes!", sone));
286 for (SimpleXML likedReplyIdXml : likeReplyIdsXml.getNodes("reply-like")) {
287 String replyId = likedReplyIdXml.getValue();
288 likedReplyIds.add(replyId);
293 SimpleXML albumsXml = soneXml.getNode("albums");
294 Map<String, Album> albums = Maps.newHashMap();
295 if (albumsXml != null) {
296 for (SimpleXML albumXml : albumsXml.getNodes("album")) {
297 String id = albumXml.getValue("id", null);
298 String parentId = albumXml.getValue("parent", null);
299 String title = albumXml.getValue("title", null);
300 String description = albumXml.getValue("description", "");
301 String albumImageId = albumXml.getValue("album-image", null);
302 if ((id == null) || (title == null) || (description == null)) {
303 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid album!", sone));
306 Album parent = sone.getRootAlbum();
307 if (parentId != null) {
308 parent = albums.get(parentId);
309 if (parent == null) {
310 logger.log(Level.WARNING, String.format("Downloaded Sone %s has album with invalid parent!", sone));
314 Album album = parent.newAlbumBuilder().withId(id).build().modify().setTitle(title).setDescription(description).update();
315 albums.put(album.getId(), album);
316 SimpleXML imagesXml = albumXml.getNode("images");
317 if (imagesXml != null) {
318 for (SimpleXML imageXml : imagesXml.getNodes("image")) {
319 String imageId = imageXml.getValue("id", null);
320 String imageCreationTimeString = imageXml.getValue("creation-time", null);
321 String imageKey = imageXml.getValue("key", null);
322 String imageTitle = imageXml.getValue("title", null);
323 String imageDescription = imageXml.getValue("description", "");
324 String imageWidthString = imageXml.getValue("width", null);
325 String imageHeightString = imageXml.getValue("height", null);
326 if ((imageId == null) || (imageCreationTimeString == null) || (imageKey == null) || (imageTitle == null) || (imageWidthString == null) || (imageHeightString == null)) {
327 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains invalid images!", sone));
330 long creationTime = Numbers.safeParseLong(imageCreationTimeString, 0L);
331 int imageWidth = Numbers.safeParseInteger(imageWidthString, 0);
332 int imageHeight = Numbers.safeParseInteger(imageHeightString, 0);
333 if ((imageWidth < 1) || (imageHeight < 1)) {
334 logger.log(Level.WARNING, String.format("Downloaded Sone %s contains image %s with invalid dimensions (%s, %s)!", sone, imageId, imageWidthString, imageHeightString));
337 Image image = album.newImageBuilder().withId(imageId).at(imageKey).created(creationTime).sized(imageWidth, imageHeight).build(Optional.<ImageCreated>absent());
338 image = image.modify().setTitle(imageTitle).setDescription(imageDescription).update();
341 album.modify().setAlbumImage(albumImageId).update();
345 /* process avatar. */
346 if (avatarId != null) {
347 profile.setAvatar(core.getImage(avatarId).orNull());
350 /* okay, apparently everything was parsed correctly. Now import. */
351 sone.setProfile(profile);
352 sone.setPosts(posts);
353 sone.setReplies(replies);
354 sone.setLikePostIds(likedPostIds);
355 sone.setLikeReplyIds(likedReplyIds);