Detect if a Sone has been changed back to the previous insert state.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneInserter.java
1 /*
2  * FreenetSone - SoneInserter.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.InputStreamReader;
21 import java.io.StringWriter;
22 import java.nio.charset.Charset;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Map;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import net.pterodactylus.sone.core.Core.SoneStatus;
31 import net.pterodactylus.sone.data.Post;
32 import net.pterodactylus.sone.data.Reply;
33 import net.pterodactylus.sone.data.Sone;
34 import net.pterodactylus.sone.freenet.StringBucket;
35 import net.pterodactylus.util.io.Closer;
36 import net.pterodactylus.util.logging.Logging;
37 import net.pterodactylus.util.service.AbstractService;
38 import net.pterodactylus.util.template.DefaultTemplateFactory;
39 import net.pterodactylus.util.template.ReflectionAccessor;
40 import net.pterodactylus.util.template.Template;
41 import net.pterodactylus.util.template.TemplateException;
42 import net.pterodactylus.util.template.XmlFilter;
43 import freenet.client.async.ManifestElement;
44 import freenet.keys.FreenetURI;
45
46 /**
47  * A Sone inserter is responsible for inserting a Sone if it has changed.
48  *
49  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50  */
51 public class SoneInserter extends AbstractService {
52
53         /** The logger. */
54         private static final Logger logger = Logging.getLogger(SoneInserter.class);
55
56         /** The insertion delay (in seconds). */
57         private static volatile int insertionDelay = 60;
58
59         /** The template factory used to create the templates. */
60         private static final DefaultTemplateFactory templateFactory = new DefaultTemplateFactory();
61
62         static {
63                 templateFactory.addAccessor(Object.class, new ReflectionAccessor());
64                 templateFactory.addFilter("xml", new XmlFilter());
65         }
66
67         /** The UTF-8 charset. */
68         private static final Charset utf8Charset = Charset.forName("UTF-8");
69
70         /** The core. */
71         private final Core core;
72
73         /** The Freenet interface. */
74         private final FreenetInterface freenetInterface;
75
76         /** The Sone to insert. */
77         private final Sone sone;
78
79         /** Whether a modification has been detected. */
80         private volatile boolean modified = false;
81
82         /** The fingerprint of the last insert. */
83         private volatile String lastInsertFingerprint;
84
85         /**
86          * Creates a new Sone inserter.
87          *
88          * @param core
89          *            The core
90          * @param freenetInterface
91          *            The freenet interface
92          * @param sone
93          *            The Sone to insert
94          */
95         public SoneInserter(Core core, FreenetInterface freenetInterface, Sone sone) {
96                 super("Sone Inserter for “" + sone.getName() + "”", false);
97                 this.core = core;
98                 this.freenetInterface = freenetInterface;
99                 this.sone = sone;
100         }
101
102         //
103         // ACCESSORS
104         //
105
106         /**
107          * Changes the insertion delay, i.e. the time the Sone inserter waits after
108          * it has noticed a Sone modification before it starts the insert.
109          *
110          * @param insertionDelay
111          *            The insertion delay (in seconds)
112          */
113         public static void setInsertionDelay(int insertionDelay) {
114                 SoneInserter.insertionDelay = insertionDelay;
115         }
116
117         /**
118          * Returns the fingerprint of the last insert.
119          *
120          * @return The fingerprint of the last insert
121          */
122         public String getLastInsertFingerprint() {
123                 return lastInsertFingerprint;
124         }
125
126         /**
127          * Sets the fingerprint of the last insert.
128          *
129          * @param lastInsertFingerprint
130          *            The fingerprint of the last insert
131          */
132         public void setLastInsertFingerprint(String lastInsertFingerprint) {
133                 this.lastInsertFingerprint = lastInsertFingerprint;
134         }
135
136         /**
137          * Returns whether the Sone inserter has detected a modification of the
138          * Sone.
139          *
140          * @return {@code true} if the Sone has been modified, {@code false}
141          *         otherwise
142          */
143         public boolean isModified() {
144                 return modified;
145         }
146
147         //
148         // SERVICE METHODS
149         //
150
151         /**
152          * {@inheritDoc}
153          */
154         @Override
155         protected void serviceRun() {
156                 long lastModificationTime = 0;
157                 String lastFingerprint = "";
158                 while (!shouldStop()) {
159                         /* check every seconds. */
160                         sleep(1000);
161
162                         InsertInformation insertInformation = null;
163                         synchronized (sone) {
164                                 String fingerprint = sone.getFingerprint();
165                                 if (!fingerprint.equals(lastFingerprint)) {
166                                         if (fingerprint.equals(lastInsertFingerprint)) {
167                                                 modified = false;
168                                                 lastModificationTime = 0;
169                                                 logger.log(Level.FINE, "Sone %s has been reverted to last insert state.", sone);
170                                         } else {
171                                                 lastModificationTime = System.currentTimeMillis();
172                                                 modified = true;
173                                                 sone.setTime(lastModificationTime);
174                                                 logger.log(Level.FINE, "Sone %s has been modified, waiting %d seconds before inserting.", new Object[] { sone.getName(), insertionDelay });
175                                         }
176                                         lastFingerprint = fingerprint;
177                                 }
178                                 if (modified && (lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
179                                         lastInsertFingerprint = fingerprint;
180                                         insertInformation = new InsertInformation(sone);
181                                 }
182                         }
183
184                         if (insertInformation != null) {
185                                 logger.log(Level.INFO, "Inserting Sone “%s”…", new Object[] { sone.getName() });
186
187                                 boolean success = false;
188                                 try {
189                                         core.setSoneStatus(sone, SoneStatus.inserting);
190                                         FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri().setKeyType("USK").setSuggestedEdition(0), insertInformation.generateManifestEntries(), "index.html");
191                                         /* at this point we might already be stopped. */
192                                         if (shouldStop()) {
193                                                 /* if so, bail out, don’t change anything. */
194                                                 break;
195                                         }
196                                         sone.setLatestEdition(finalUri.getEdition());
197                                         success = true;
198                                         logger.log(Level.INFO, "Inserted Sone “%s” at %s.", new Object[] { sone.getName(), finalUri });
199                                 } catch (SoneException se1) {
200                                         logger.log(Level.WARNING, "Could not insert Sone “" + sone.getName() + "”!", se1);
201                                 } finally {
202                                         core.setSoneStatus(sone, SoneStatus.idle);
203                                 }
204
205                                 /*
206                                  * reset modification counter if Sone has not been modified
207                                  * while it was inserted.
208                                  */
209                                 if (success) {
210                                         synchronized (sone) {
211                                                 if (lastInsertFingerprint.equals(sone.getFingerprint())) {
212                                                         logger.log(Level.FINE, "Sone “%s” was not modified further, resetting counter…", new Object[] { sone });
213                                                         core.saveSone(sone);
214                                                         lastModificationTime = 0;
215                                                         modified = false;
216                                                 }
217                                         }
218                                 }
219                         }
220                 }
221         }
222
223         /**
224          * Container for information that are required to insert a Sone. This
225          * container merely exists to copy all relevant data without holding a lock
226          * on the {@link Sone} object for too long.
227          *
228          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
229          */
230         private class InsertInformation {
231
232                 /** All properties of the Sone, copied for thread safety. */
233                 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
234
235                 /**
236                  * Creates a new insert information container.
237                  *
238                  * @param sone
239                  *            The sone to insert
240                  */
241                 public InsertInformation(Sone sone) {
242                         soneProperties.put("id", sone.getId());
243                         soneProperties.put("name", sone.getName());
244                         soneProperties.put("time", sone.getTime());
245                         soneProperties.put("requestUri", sone.getRequestUri());
246                         soneProperties.put("insertUri", sone.getInsertUri());
247                         soneProperties.put("profile", sone.getProfile());
248                         soneProperties.put("posts", new ArrayList<Post>(sone.getPosts()));
249                         soneProperties.put("replies", new HashSet<Reply>(sone.getReplies()));
250                         soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
251                         soneProperties.put("likeReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
252                 }
253
254                 //
255                 // ACCESSORS
256                 //
257
258                 /**
259                  * Returns the insert URI of the Sone.
260                  *
261                  * @return The insert URI of the Sone
262                  */
263                 public FreenetURI getInsertUri() {
264                         return (FreenetURI) soneProperties.get("insertUri");
265                 }
266
267                 //
268                 // ACTIONS
269                 //
270
271                 /**
272                  * Generates all manifest entries required to insert this Sone.
273                  *
274                  * @return The manifest entries for the Sone insert
275                  */
276                 public HashMap<String, Object> generateManifestEntries() {
277                         HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
278
279                         /* first, create an index.html. */
280                         manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
281
282                         /* now, store the sone. */
283                         manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
284
285                         return manifestEntries;
286                 }
287
288                 //
289                 // PRIVATE METHODS
290                 //
291
292                 /**
293                  * Creates a new manifest element.
294                  *
295                  * @param name
296                  *            The name of the file
297                  * @param contentType
298                  *            The content type of the file
299                  * @param templateName
300                  *            The name of the template to render
301                  * @return The manifest element
302                  */
303                 @SuppressWarnings("synthetic-access")
304                 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
305                         InputStreamReader templateInputStreamReader;
306                         Template template = templateFactory.createTemplate(templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset));
307                         try {
308                                 template.parse();
309                         } catch (TemplateException te1) {
310                                 logger.log(Level.SEVERE, "Could not parse template “" + templateName + "”!", te1);
311                                 return null;
312                         } finally {
313                                 Closer.close(templateInputStreamReader);
314                         }
315
316                         template.set("currentSone", soneProperties);
317                         StringWriter writer = new StringWriter();
318                         StringBucket bucket = null;
319                         try {
320                                 template.render(writer);
321                                 bucket = new StringBucket(writer.toString(), utf8Charset);
322                                 return new ManifestElement(name, bucket, contentType, bucket.size());
323                         } catch (TemplateException te1) {
324                                 logger.log(Level.SEVERE, "Could not render template “" + templateName + "”!", te1);
325                                 return null;
326                         } finally {
327                                 Closer.close(writer);
328                                 if (bucket != null) {
329                                         bucket.free();
330                                 }
331                         }
332                 }
333
334         }
335
336 }