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