Add parsing stub.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneDownloader.java
1 /*
2  * Sone - SoneDownloader.java - Copyright © 2010 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.core;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.util.HashSet;
23 import java.util.Set;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26
27 import net.pterodactylus.sone.data.Post;
28 import net.pterodactylus.sone.data.Profile;
29 import net.pterodactylus.sone.data.Reply;
30 import net.pterodactylus.sone.data.Sone;
31 import net.pterodactylus.util.io.Closer;
32 import net.pterodactylus.util.logging.Logging;
33 import net.pterodactylus.util.service.AbstractService;
34 import net.pterodactylus.util.xml.SimpleXML;
35 import net.pterodactylus.util.xml.XML;
36
37 import org.w3c.dom.Document;
38
39 import freenet.client.FetchResult;
40 import freenet.support.api.Bucket;
41
42 /**
43  * The Sone downloader is responsible for download Sones as they are updated.
44  *
45  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46  */
47 public class SoneDownloader extends AbstractService {
48
49         /** The logger. */
50         private static final Logger logger = Logging.getLogger(SoneDownloader.class);
51
52         /** The Freenet interface. */
53         private final FreenetInterface freenetInterface;
54
55         /** The sones to update. */
56         private final Set<Sone> sones = new HashSet<Sone>();
57
58         /**
59          * Creates a new Sone downloader.
60          *
61          * @param freenetInterface
62          *            The Freenet interface
63          */
64         public SoneDownloader(FreenetInterface freenetInterface) {
65                 super("Sone Downloader");
66                 this.freenetInterface = freenetInterface;
67         }
68
69         //
70         // ACTIONS
71         //
72
73         /**
74          * Adds the given Sone to the set of Sones that will be watched for updates.
75          *
76          * @param sone
77          *            The Sone to add
78          */
79         public void addSone(Sone sone) {
80                 if (sones.add(sone)) {
81                         freenetInterface.registerUsk(sone, this);
82                 }
83         }
84
85         /**
86          * Fetches the updated Sone. This method is a callback method for
87          * {@link FreenetInterface#registerUsk(Sone, SoneDownloader)}.
88          *
89          * @param sone
90          *            The Sone to fetch
91          */
92         public void fetchSone(Sone sone) {
93                 logger.log(Level.FINE, "Starting fetch for Sone “%s” from %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
94                 FetchResult fetchResult = freenetInterface.fetchUri(sone.getRequestUri().setMetaString(new String[] { "sone.xml" }));
95                 logger.log(Level.FINEST, "Got %d bytes back.", fetchResult.size());
96                 updateSoneFromXml(sone, fetchResult);
97         }
98
99         //
100         // SERVICE METHODS
101         //
102
103         /**
104          * {@inheritDoc}
105          */
106         @Override
107         protected void serviceStop() {
108                 for (Sone sone : sones) {
109                         freenetInterface.unregisterUsk(sone);
110                 }
111         }
112
113         //
114         // PRIVATE METHODS
115         //
116
117         /**
118          * Updates the contents of the given Sone from the given fetch result.
119          *
120          * @param sone
121          *            The Sone to update
122          * @param fetchResult
123          *            The fetch result
124          */
125         private void updateSoneFromXml(Sone sone, FetchResult fetchResult) {
126                 logger.log(Level.FINEST, "Persing FetchResult (%d bytes, %s) for %s…", new Object[] { fetchResult.size(), fetchResult.getMimeType(), sone });
127                 /* TODO - impose a size limit? */
128                 InputStream xmlInputStream = null;
129                 Bucket xmlBucket = null;
130                 try {
131                         xmlBucket = fetchResult.asBucket();
132                         xmlInputStream = xmlBucket.getInputStream();
133                         Document document = XML.transformToDocument(xmlInputStream);
134                         SimpleXML soneXml = SimpleXML.fromDocument(document);
135
136                         /* check ID. */
137                         String soneId = soneXml.getValue("id", null);
138                         if (!sone.getId().equals(soneId)) {
139                                 /* TODO - mark Sone as bad. */
140                                 logger.log(Level.WARNING, "Downloaded ID for Sone %s (%s) does not match known ID (%s)!", new Object[] { sone, sone.getId(), soneId });
141                                 return;
142                         }
143
144                         String soneName = soneXml.getValue("name", null);
145                         if (soneName == null) {
146                                 /* TODO - mark Sone as bad. */
147                                 logger.log(Level.WARNING, "Downloaded name for Sone %s was null!", new Object[] { sone });
148                                 return;
149                         }
150
151                         SimpleXML profileXml = soneXml.getNode("profile");
152                         if (profileXml == null) {
153                                 /* TODO - mark Sone as bad. */
154                                 logger.log(Level.WARNING, "Downloaded Sone %s has no profile!", new Object[] { sone });
155                                 return;
156                         }
157
158                         /* parse profile. */
159                         String profileFirstName = profileXml.getValue("first-name", null);
160                         String profileMiddleName = profileXml.getValue("middle-name", null);
161                         String profileLastName = profileXml.getValue("last-name", null);
162                         Profile profile = new Profile().setFirstName(profileFirstName).setMiddleName(profileMiddleName).setLastName(profileLastName);
163
164                         /* parse posts. */
165                         SimpleXML postsXml = soneXml.getNode("posts");
166                         if (postsXml == null) {
167                                 /* TODO - mark Sone as bad. */
168                                 logger.log(Level.WARNING, "Downloaded Sone %s has no posts!", new Object[] { sone });
169                                 return;
170                         }
171
172                         Set<Post> posts = new HashSet<Post>();
173                         for (SimpleXML postXml : postsXml.getNodes("post")) {
174                                 String postId = postXml.getValue("id", null);
175                                 String postTime = postXml.getValue("time", null);
176                                 String postText = postXml.getValue("text", null);
177                                 if ((postId == null) || (postTime == null) || (postText == null)) {
178                                         /* TODO - mark Sone as bad. */
179                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with missing data! ID: %s, Time: %s, Text: %s", new Object[] { sone, postId, postTime, postText });
180                                         return;
181                                 }
182                                 try {
183                                         posts.add(new Post(postId, sone, Long.parseLong(postTime), postText));
184                                 } catch (NumberFormatException nfe1) {
185                                         /* TODO - mark Sone as bad. */
186                                         logger.log(Level.WARNING, "Downloaded post for Sone %s with invalid time: %s", new Object[] { sone, postTime });
187                                         return;
188                                 }
189                         }
190
191                         /* parse replies. */
192                         SimpleXML repliesXml = soneXml.getNode("replies");
193                         if (repliesXml == null) {
194                                 /* TODO - mark Sone as bad. */
195                                 logger.log(Level.WARNING, "Downloaded Sone %s has no replies!", new Object[] { sone });
196                                 return;
197                         }
198
199                         Set<Reply> replies = new HashSet<Reply>();
200                         for (SimpleXML replyXml : repliesXml.getNodes("reply")) {
201                                 String replyId = replyXml.getValue("id", null);
202                                 String replyPostId = replyXml.getValue("post-id", null);
203                                 String replyTime = replyXml.getValue("time", null);
204                                 String replyText = replyXml.getValue("text", null);
205                                 /* TODO - finish! */
206                         }
207                 } catch (IOException ioe1) {
208                         logger.log(Level.WARNING, "Could not read XML file from " + sone + "!", ioe1);
209                 } finally {
210                         if (xmlBucket != null) {
211                                 xmlBucket.free();
212                         }
213                         Closer.close(xmlInputStream);
214                 }
215         }
216
217 }