Merge branch 'feature/purge-db4o' into develop
[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
23 import java.io.InputStreamReader;
24 import java.io.StringWriter;
25 import java.nio.charset.Charset;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Map;
29 import java.util.Set;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
32
33 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
34 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
35 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
36 import net.pterodactylus.sone.data.Album;
37 import net.pterodactylus.sone.data.Post;
38 import net.pterodactylus.sone.data.Reply;
39 import net.pterodactylus.sone.data.Sone;
40 import net.pterodactylus.sone.data.Sone.SoneStatus;
41 import net.pterodactylus.sone.main.SonePlugin;
42 import net.pterodactylus.util.io.Closer;
43 import net.pterodactylus.util.logging.Logging;
44 import net.pterodactylus.util.service.AbstractService;
45 import net.pterodactylus.util.template.HtmlFilter;
46 import net.pterodactylus.util.template.ReflectionAccessor;
47 import net.pterodactylus.util.template.Template;
48 import net.pterodactylus.util.template.TemplateContext;
49 import net.pterodactylus.util.template.TemplateContextFactory;
50 import net.pterodactylus.util.template.TemplateException;
51 import net.pterodactylus.util.template.TemplateParser;
52 import net.pterodactylus.util.template.XmlFilter;
53
54 import com.google.common.base.Charsets;
55 import com.google.common.collect.FluentIterable;
56 import com.google.common.collect.Ordering;
57 import com.google.common.eventbus.EventBus;
58
59 import freenet.keys.FreenetURI;
60 import freenet.support.api.Bucket;
61 import freenet.support.api.ManifestElement;
62 import freenet.support.api.RandomAccessBucket;
63 import freenet.support.io.ArrayBucket;
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         /**
191          * {@inheritDoc}
192          */
193         @Override
194         protected void serviceRun() {
195                 long lastModificationTime = 0;
196                 String lastInsertedFingerprint = lastInsertFingerprint;
197                 String lastFingerprint = "";
198                 Sone sone;
199                 while (!shouldStop()) {
200                         try {
201                                 /* check every seconds. */
202                                 sleep(1000);
203
204                                 /* don’t insert locked Sones. */
205                                 sone = this.sone;
206                                 if (core.isLocked(sone)) {
207                                         /* trigger redetection when the Sone is unlocked. */
208                                         synchronized (sone) {
209                                                 modified = !sone.getFingerprint().equals(lastInsertedFingerprint);
210                                         }
211                                         lastFingerprint = "";
212                                         lastModificationTime = 0;
213                                         continue;
214                                 }
215
216                                 InsertInformation insertInformation = null;
217                                 synchronized (sone) {
218                                         String fingerprint = sone.getFingerprint();
219                                         if (!fingerprint.equals(lastFingerprint)) {
220                                                 if (fingerprint.equals(lastInsertedFingerprint)) {
221                                                         modified = false;
222                                                         lastModificationTime = 0;
223                                                         logger.log(Level.FINE, String.format("Sone %s has been reverted to last insert state.", sone));
224                                                 } else {
225                                                         lastModificationTime = System.currentTimeMillis();
226                                                         modified = true;
227                                                         logger.log(Level.FINE, String.format("Sone %s has been modified, waiting %d seconds before inserting.", sone.getName(), insertionDelay));
228                                                 }
229                                                 lastFingerprint = fingerprint;
230                                         }
231                                         if (modified && (lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
232                                                 lastInsertedFingerprint = fingerprint;
233                                                 insertInformation = new InsertInformation(sone);
234                                         }
235                                 }
236
237                                 if (insertInformation != null) {
238                                         logger.log(Level.INFO, String.format("Inserting Sone “%s”…", sone.getName()));
239
240                                         boolean success = false;
241                                         try {
242                                                 sone.setStatus(SoneStatus.inserting);
243                                                 long insertTime = System.currentTimeMillis();
244                                                 insertInformation.setTime(insertTime);
245                                                 eventBus.post(new SoneInsertingEvent(sone));
246                                                 FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
247                                                 eventBus.post(new SoneInsertedEvent(sone, System.currentTimeMillis() - insertTime));
248                                                 /* at this point we might already be stopped. */
249                                                 if (shouldStop()) {
250                                                         /* if so, bail out, don’t change anything. */
251                                                         break;
252                                                 }
253                                                 sone.setTime(insertTime);
254                                                 sone.setLatestEdition(finalUri.getEdition());
255                                                 core.touchConfiguration();
256                                                 success = true;
257                                                 logger.log(Level.INFO, String.format("Inserted Sone “%s” at %s.", sone.getName(), finalUri));
258                                         } catch (SoneException se1) {
259                                                 eventBus.post(new SoneInsertAbortedEvent(sone, se1));
260                                                 logger.log(Level.WARNING, String.format("Could not insert Sone “%s”!", sone.getName()), se1);
261                                         } finally {
262                                                 insertInformation.close();
263                                                 sone.setStatus(SoneStatus.idle);
264                                         }
265
266                                         /*
267                                          * reset modification counter if Sone has not been modified
268                                          * while it was inserted.
269                                          */
270                                         if (success) {
271                                                 synchronized (sone) {
272                                                         if (lastInsertedFingerprint.equals(sone.getFingerprint())) {
273                                                                 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
274                                                                 lastModificationTime = 0;
275                                                                 lastInsertFingerprint = lastInsertedFingerprint;
276                                                                 core.touchConfiguration();
277                                                                 modified = false;
278                                                         }
279                                                 }
280                                         }
281                                 }
282                         } catch (Throwable t1) {
283                                 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
284                         }
285                 }
286         }
287
288         /**
289          * Container for information that are required to insert a Sone. This
290          * container merely exists to copy all relevant data without holding a lock
291          * on the {@link Sone} object for too long.
292          *
293          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
294          */
295         private class InsertInformation {
296
297                 /** All properties of the Sone, copied for thread safety. */
298                 private final Map<String, Object> soneProperties = new HashMap<String, Object>();
299                 private final Set<Bucket> buckets = new HashSet<Bucket>();
300
301                 /**
302                  * Creates a new insert information container.
303                  *
304                  * @param sone
305                  *            The sone to insert
306                  */
307                 public InsertInformation(Sone sone) {
308                         soneProperties.put("id", sone.getId());
309                         soneProperties.put("name", sone.getName());
310                         soneProperties.put("time", sone.getTime());
311                         soneProperties.put("requestUri", sone.getRequestUri());
312                         soneProperties.put("insertUri", sone.getInsertUri());
313                         soneProperties.put("profile", sone.getProfile());
314                         soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
315                         soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
316                         soneProperties.put("likedPostIds", new HashSet<String>(sone.getLikedPostIds()));
317                         soneProperties.put("likedReplyIds", new HashSet<String>(sone.getLikedReplyIds()));
318                         soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
319                 }
320
321                 //
322                 // ACCESSORS
323                 //
324
325                 /**
326                  * Returns the insert URI of the Sone.
327                  *
328                  * @return The insert URI of the Sone
329                  */
330                 public FreenetURI getInsertUri() {
331                         return (FreenetURI) soneProperties.get("insertUri");
332                 }
333
334                 /**
335                  * Sets the time of the Sone at the time of the insert.
336                  *
337                  * @param time
338                  *            The time of the Sone
339                  */
340                 public void setTime(long time) {
341                         soneProperties.put("time", time);
342                 }
343
344                 //
345                 // ACTIONS
346                 //
347
348                 /**
349                  * Generates all manifest entries required to insert this Sone.
350                  *
351                  * @return The manifest entries for the Sone insert
352                  */
353                 public HashMap<String, Object> generateManifestEntries() {
354                         HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
355
356                         /* first, create an index.html. */
357                         manifestEntries.put("index.html", createManifestElement("index.html", "text/html; charset=utf-8", "/templates/insert/index.html"));
358
359                         /* now, store the sone. */
360                         manifestEntries.put("sone.xml", createManifestElement("sone.xml", "text/xml; charset=utf-8", "/templates/insert/sone.xml"));
361
362                         return manifestEntries;
363                 }
364
365                 //
366                 // PRIVATE METHODS
367                 //
368
369                 /**
370                  * Creates a new manifest element.
371                  *
372                  * @param name
373                  *            The name of the file
374                  * @param contentType
375                  *            The content type of the file
376                  * @param templateName
377                  *            The name of the template to render
378                  * @return The manifest element
379                  */
380                 @SuppressWarnings("synthetic-access")
381                 private ManifestElement createManifestElement(String name, String contentType, String templateName) {
382                         InputStreamReader templateInputStreamReader = null;
383                         Template template;
384                         try {
385                                 templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset);
386                                 template = TemplateParser.parse(templateInputStreamReader);
387                         } catch (TemplateException te1) {
388                                 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
389                                 return null;
390                         } finally {
391                                 Closer.close(templateInputStreamReader);
392                         }
393
394                         TemplateContext templateContext = templateContextFactory.createTemplateContext();
395                         templateContext.set("core", core);
396                         templateContext.set("currentSone", soneProperties);
397                         templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
398                         templateContext.set("version", SonePlugin.VERSION);
399                         StringWriter writer = new StringWriter();
400                         try {
401                                 template.render(templateContext, writer);
402                                 RandomAccessBucket bucket = new ArrayBucket(writer.toString().getBytes(Charsets.UTF_8));
403                                 buckets.add(bucket);
404                                 return new ManifestElement(name, bucket, contentType, bucket.size());
405                         } catch (TemplateException te1) {
406                                 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
407                                 return null;
408                         } finally {
409                                 Closer.close(writer);
410                         }
411                 }
412
413                 public void close() {
414                         for (Bucket bucket : buckets) {
415                                 bucket.free();
416                         }
417                 }
418
419         }
420
421 }