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