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