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