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