Free all buckets after the insert has finished.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / SoneInserter.java
1 /*
2  * Sone - SoneInserter.java - Copyright © 2010–2013 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 static com.google.common.base.Preconditions.checkArgument;
21 import static net.pterodactylus.sone.data.Album.NOT_EMPTY;
22 import static net.pterodactylus.sone.data.Sone.TO_FREENET_URI;
23 import static net.pterodactylus.sone.data.Sone.TO_INSERT_URI;
24
25 import java.io.InputStreamReader;
26 import java.io.StringWriter;
27 import java.nio.charset.Charset;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.Map;
31 import java.util.Set;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
34
35 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
36 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
37 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
38 import net.pterodactylus.sone.data.Album;
39 import net.pterodactylus.sone.data.Post;
40 import net.pterodactylus.sone.data.Reply;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.data.Sone.SoneStatus;
43 import net.pterodactylus.sone.freenet.StringBucket;
44 import net.pterodactylus.sone.main.SonePlugin;
45 import net.pterodactylus.util.io.Closer;
46 import net.pterodactylus.util.logging.Logging;
47 import net.pterodactylus.util.service.AbstractService;
48 import net.pterodactylus.util.template.HtmlFilter;
49 import net.pterodactylus.util.template.ReflectionAccessor;
50 import net.pterodactylus.util.template.Template;
51 import net.pterodactylus.util.template.TemplateContext;
52 import net.pterodactylus.util.template.TemplateContextFactory;
53 import net.pterodactylus.util.template.TemplateException;
54 import net.pterodactylus.util.template.TemplateParser;
55 import net.pterodactylus.util.template.XmlFilter;
56
57 import freenet.client.async.ManifestElement;
58 import freenet.keys.FreenetURI;
59 import freenet.support.api.Bucket;
60
61 import com.google.common.collect.FluentIterable;
62 import com.google.common.collect.Ordering;
63 import com.google.common.eventbus.EventBus;
64
65 /**
66  * A Sone inserter is responsible for inserting a Sone if it has changed.
67  *
68  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
69  */
70 public class SoneInserter extends AbstractService {
71
72         /** The logger. */
73         private static final Logger logger = Logging.getLogger(SoneInserter.class);
74
75         /** The insertion delay (in seconds). */
76         private static volatile int insertionDelay = 60;
77
78         /** The template factory used to create the templates. */
79         private static final TemplateContextFactory templateContextFactory = new TemplateContextFactory();
80
81         static {
82                 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
83                 templateContextFactory.addFilter("xml", new XmlFilter());
84                 templateContextFactory.addFilter("html", new HtmlFilter());
85         }
86
87         /** The UTF-8 charset. */
88         private static final Charset utf8Charset = Charset.forName("UTF-8");
89
90         /** The core. */
91         private final Core core;
92
93         /** The event bus. */
94         private final EventBus eventBus;
95
96         /** The Freenet interface. */
97         private final FreenetInterface freenetInterface;
98
99         /** The Sone to insert. */
100         private volatile Sone sone;
101
102         /** Whether a modification has been detected. */
103         private volatile boolean modified = false;
104
105         /** The fingerprint of the last insert. */
106         private volatile String lastInsertFingerprint;
107
108         /**
109          * Creates a new Sone inserter.
110          *
111          * @param core
112          *            The core
113          * @param eventBus
114          *            The event bus
115          * @param freenetInterface
116          *            The freenet interface
117          * @param sone
118          *            The Sone to insert
119          */
120         public SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone) {
121                 super("Sone Inserter for “" + sone.getName() + "”", false);
122                 this.core = core;
123                 this.eventBus = eventBus;
124                 this.freenetInterface = freenetInterface;
125                 this.sone = sone;
126         }
127
128         //
129         // ACCESSORS
130         //
131
132         /**
133          * Sets the Sone to insert.
134          *
135          * @param sone
136          *              The Sone to insert
137          * @return This Sone inserter
138          */
139         public SoneInserter setSone(Sone sone) {
140                 checkArgument((this.sone == null) || sone.equals(this.sone), "Sone to insert can not be set to a different Sone");
141                 this.sone = sone;
142                 return this;
143         }
144
145         /**
146          * Changes the insertion delay, i.e. the time the Sone inserter waits after it
147          * has noticed a Sone modification before it starts the insert.
148          *
149          * @param insertionDelay
150          *            The insertion delay (in seconds)
151          */
152         public static void setInsertionDelay(int insertionDelay) {
153                 SoneInserter.insertionDelay = insertionDelay;
154         }
155
156         /**
157          * Returns the fingerprint of the last insert.
158          *
159          * @return The fingerprint of the last insert
160          */
161         public String getLastInsertFingerprint() {
162                 return lastInsertFingerprint;
163         }
164
165         /**
166          * Sets the fingerprint of the last insert.
167          *
168          * @param lastInsertFingerprint
169          *            The fingerprint of the last insert
170          */
171         public void setLastInsertFingerprint(String lastInsertFingerprint) {
172                 this.lastInsertFingerprint = lastInsertFingerprint;
173         }
174
175         /**
176          * Returns whether the Sone inserter has detected a modification of the
177          * Sone.
178          *
179          * @return {@code true} if the Sone has been modified, {@code false}
180          *         otherwise
181          */
182         public boolean isModified() {
183                 return modified;
184         }
185
186         //
187         // SERVICE METHODS
188         //
189
190         @Override
191         protected void serviceRun() {
192                 long lastModificationTime = 0;
193                 String lastInsertedFingerprint = lastInsertFingerprint;
194                 String lastFingerprint = "";
195                 Sone sone;
196                 while (!shouldStop()) {
197                         try {
198                                 /* check every seconds. */
199                                 sleep(1000);
200
201                                 /* don’t insert locked Sones. */
202                                 sone = this.sone;
203                                 if (core.isLocked(sone)) {
204                                         /* trigger redetection when the Sone is unlocked. */
205                                         synchronized (sone) {
206                                                 modified = !sone.getFingerprint().equals(lastInsertedFingerprint);
207                                         }
208                                         lastFingerprint = "";
209                                         lastModificationTime = 0;
210                                         continue;
211                                 }
212
213                                 InsertInformation insertInformation = null;
214                                 synchronized (sone) {
215                                         String fingerprint = sone.getFingerprint();
216                                         if (!fingerprint.equals(lastFingerprint)) {
217                                                 if (fingerprint.equals(lastInsertedFingerprint)) {
218                                                         modified = false;
219                                                         lastModificationTime = 0;
220                                                         logger.log(Level.FINE, String.format("Sone %s has been reverted to last insert state.", sone));
221                                                 } else {
222                                                         lastModificationTime = System.currentTimeMillis();
223                                                         modified = true;
224                                                         logger.log(Level.FINE, String.format("Sone %s has been modified, waiting %d seconds before inserting.", sone.getName(), insertionDelay));
225                                                 }
226                                                 lastFingerprint = fingerprint;
227                                         }
228                                         if (modified && (lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
229                                                 lastInsertedFingerprint = fingerprint;
230                                                 insertInformation = new InsertInformation(sone);
231                                         }
232                                 }
233
234                                 if (insertInformation != null) {
235                                         logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
236
237                                         boolean success = false;
238                                         try {
239                                                 sone.setStatus(SoneStatus.inserting);
240                                                 long insertTime = System.currentTimeMillis();
241                                                 insertInformation.setTime(insertTime);
242                                                 eventBus.post(new SoneInsertingEvent(sone));
243                                                 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
244                                                 eventBus.post(new SoneInsertedEvent(sone, System.currentTimeMillis() - insertTime));
245                                                 /* at this point we might already be stopped. */
246                                                 if (shouldStop()) {
247                                                         /* if so, bail out, don’t change anything. */
248                                                         break;
249                                                 }
250                                                 sone.setTime(insertTime);
251                                                 sone.modify().setLatestEdition(finalUri.getEdition()).update();
252                                                 core.touchConfiguration();
253                                                 success = true;
254                                                 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
255                                         } catch (SoneException se1) {
256                                                 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
257                                                 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
258                                         } finally {
259                                                 insertInformation.freeBuckets();
260                                                 sone.setStatus(SoneStatus.idle);
261                                         }
262
263                                         /*
264                                          * reset modification counter if Sone has not been modified
265                                          * while it was inserted.
266                                          */
267                                         if (success) {
268                                                 synchronized (sone) {
269                                                         if (lastInsertedFingerprint.equals(sone.getFingerprint())) {
270                                                                 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
271                                                                 lastModificationTime = 0;
272                                                                 lastInsertFingerprint = lastInsertedFingerprint;
273                                                                 core.touchConfiguration();
274                                                                 modified = false;
275                                                         }
276                                                 }
277                                         }
278                                 }
279                         } catch (Throwable t1) {
280                                 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
281                         }
282                 }
283         }
284
285         /**
286          * Container for information that are required to insert a Sone. This
287          * container merely exists to copy all relevant data without holding a lock
288          * on the {@link Sone} object for too long.
289          *
290          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
291          */
292         private class InsertInformation {
293
294                 /** All properties of the Sone, copied for thread safety. */
295                 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
296                 private final Set<Bucket> buckets = new HashSet<Bucket>();
297
298                 /**
299                  * Creates a new insert information container.
300                  *
301                  * @param sone
302                  *            The sone to insert
303                  */
304                 public InsertInformation(Sone sone) {
305                         soneProperties.put("id", sone.getId());
306                         soneProperties.put("name", sone.getName());
307                         soneProperties.put("time", sone.getTime());
308                         soneProperties.put("requestUri", TO_FREENET_URI.apply(sone));
309                         soneProperties.put("insertUri", TO_INSERT_URI.apply(sone));
310                         soneProperties.put("profile", sone.getProfile());
311                         soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
312                         soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
313                         soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
314                         soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
315                         soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
316                 }
317
318                 //
319                 // ACCESSORS
320                 //
321
322                 /**
323                  * Returns the insert URI of the Sone.
324                  *
325                  * @return The insert URI of the Sone
326                  */
327                 public FreenetURI getInsertUri() {
328                         return (FreenetURI) soneProperties.get("insertUri");
329                 }
330
331                 /**
332                  * Sets the time of the Sone at the time of the insert.
333                  *
334                  * @param time
335                  *            The time of the Sone
336                  */
337                 public void setTime(long time) {
338                         soneProperties.put("time", time);
339                 }
340
341                 //
342                 // ACTIONS
343                 //
344
345                 /**
346                  * Generates all manifest entries required to insert this Sone.
347                  *
348                  * @return The manifest entries for the Sone insert
349                  */
350                 public HashMap<String, Object> generateManifestEntries() {
351                         HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
352
353                         /* first, create an index.html. */
354                         manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
355
356                         /* now, store the sone. */
357                         manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
358
359                         return manifestEntries;
360                 }
361
362                 public void freeBuckets() {
363                         for (Bucket bucket : buckets) {
364                                 bucket.free();
365                         }
366                 }
367
368                 //
369                 // PRIVATE METHODS
370                 //
371
372                 /**
373                  * Creates a new manifest element.
374                  *
375                  * @param name
376                  *            The name of the file
377                  * @param contentType
378                  *            The content type of the file
379                  * @param templateName
380                  *            The name of the template to render
381                  * @return The manifest element
382                  */
383                 @SuppressWarnings("synthetic-access")
384                 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
385                         InputStreamReader templateInputStreamReader = null;
386                         Template template;
387                         try {
388                                 templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset);
389                                 template = TemplateParser.parse(templateInputStreamReader);
390                         } catch (TemplateException te1) {
391                                 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
392                                 return null;
393                         } finally {
394                                 Closer.close(templateInputStreamReader);
395                         }
396
397                         TemplateContext templateContext = templateContextFactory.createTemplateContext();
398                         templateContext.set("core", core);
399                         templateContext.set("currentSone", soneProperties);
400                         templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
401                         templateContext.set("version", SonePlugin.VERSION);
402                         StringWriter writer = new StringWriter();
403                         StringBucket bucket = null;
404                         try {
405                                 template.render(templateContext, writer);
406                                 bucket = new StringBucket(writer.toString(), utf8Charset);
407                                 return new ManifestElement(name, bucket, contentType, bucket.size());
408                         } catch (TemplateException te1) {
409                                 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
410                                 return null;
411                         } finally {
412                                 Closer.close(writer);
413                         }
414                 }
415
416         }
417
418 }