Remove updated time setter from Sone, store update time in database.
[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 java.util.logging.Logger.getLogger;
23 import static net.pterodactylus.sone.data.Album.NOT_EMPTY;
24
25 import java.io.InputStream;
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.concurrent.atomic.AtomicInteger;
33 import java.util.logging.Level;
34 import java.util.logging.Logger;
35
36 import net.pterodactylus.sone.core.SoneModificationDetector.LockableFingerprintProvider;
37 import net.pterodactylus.sone.core.event.InsertionDelayChangedEvent;
38 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
39 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
40 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
41 import net.pterodactylus.sone.data.Album;
42 import net.pterodactylus.sone.data.LocalSone;
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.database.Database;
48 import net.pterodactylus.sone.freenet.StringBucket;
49 import net.pterodactylus.sone.main.SonePlugin;
50 import net.pterodactylus.util.io.Closer;
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 = getLogger("Sone.Inserter");
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         private final Database database;
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, Database database, final String soneId) {
122                 this(core, eventBus, freenetInterface, database, soneId, new SoneModificationDetector(new LockableFingerprintProvider() {
123                         @Override
124                         public boolean isLocked() {
125                                 final Optional<LocalSone> sone = core.getLocalSone(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, Database database, 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.database = database;
150                 this.soneId = soneId;
151                 this.soneModificationDetector = soneModificationDetector;
152                 this.delay = delay;
153         }
154
155         //
156         // ACCESSORS
157         //
158
159         @VisibleForTesting
160         static AtomicInteger getInsertionDelay() {
161                 return insertionDelay;
162         }
163
164         /**
165          * Changes the insertion delay, i.e. the time the Sone inserter waits after it
166          * has noticed a Sone modification before it starts the insert.
167          *
168          * @param insertionDelay
169          *            The insertion delay (in seconds)
170          */
171         private static void setInsertionDelay(int insertionDelay) {
172                 SoneInserter.insertionDelay.set(insertionDelay);
173         }
174
175         /**
176          * Returns the fingerprint of the last insert.
177          *
178          * @return The fingerprint of the last insert
179          */
180         public String getLastInsertFingerprint() {
181                 return soneModificationDetector.getOriginalFingerprint();
182         }
183
184         /**
185          * Sets the fingerprint of the last insert.
186          *
187          * @param lastInsertFingerprint
188          *            The fingerprint of the last insert
189          */
190         public void setLastInsertFingerprint(String lastInsertFingerprint) {
191                 soneModificationDetector.setFingerprint(lastInsertFingerprint);
192         }
193
194         /**
195          * Returns whether the Sone inserter has detected a modification of the
196          * Sone.
197          *
198          * @return {@code true} if the Sone has been modified, {@code false}
199          *         otherwise
200          */
201         public boolean isModified() {
202                 return soneModificationDetector.isModified();
203         }
204
205         //
206         // SERVICE METHODS
207         //
208
209         /**
210          * {@inheritDoc}
211          */
212         @Override
213         protected void serviceRun() {
214                 while (!shouldStop()) {
215                         try {
216                                 /* check every second. */
217                                 sleep(delay);
218
219                                 if (soneModificationDetector.isEligibleForInsert()) {
220                                         Optional<LocalSone> soneOptional = core.getLocalSone(soneId);
221                                         if (!soneOptional.isPresent()) {
222                                                 logger.log(Level.WARNING, format("Sone %s has disappeared, exiting inserter.", soneId));
223                                                 return;
224                                         }
225                                         LocalSone sone = soneOptional.get();
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                                                 database.updateSoneTime(sone, 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                                                 sone.setStatus(SoneStatus.idle);
251                                         }
252
253                                         /*
254                                          * reset modification counter if Sone has not been modified
255                                          * while it was inserted.
256                                          */
257                                         if (success) {
258                                                 synchronized (sone) {
259                                                         if (insertInformation.getFingerprint().equals(sone.getFingerprint())) {
260                                                                 logger.log(Level.FINE, String.format("Sone “%s” was not modified further, resetting counter…", sone));
261                                                                 soneModificationDetector.setFingerprint(insertInformation.getFingerprint());
262                                                                 core.touchConfiguration();
263                                                         }
264                                                 }
265                                         }
266                                 }
267                         } catch (Throwable t1) {
268                                 logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
269                         }
270                 }
271         }
272
273         @Subscribe
274         public void insertionDelayChanged(InsertionDelayChangedEvent insertionDelayChangedEvent) {
275                 setInsertionDelay(insertionDelayChangedEvent.getInsertionDelay());
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         @VisibleForTesting
286         class InsertInformation {
287
288                 private final String fingerprint;
289                 private final ManifestCreator manifestCreator;
290
291                 /**
292                  * Creates a new insert information container.
293                  *
294                  * @param sone
295                  *            The sone to insert
296                  */
297                 public InsertInformation(Sone sone) {
298                         this.fingerprint = sone.getFingerprint();
299                         Map<String, Object> soneProperties = new HashMap<String, Object>();
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                         manifestCreator = new ManifestCreator(core, soneProperties);
311                 }
312
313                 //
314                 // ACCESSORS
315                 //
316
317                 @VisibleForTesting
318                 String getFingerprint() {
319                         return fingerprint;
320                 }
321
322                 //
323                 // ACTIONS
324                 //
325
326                 /**
327                  * Generates all manifest entries required to insert this Sone.
328                  *
329                  * @return The manifest entries for the Sone insert
330                  */
331                 public HashMap<String, Object> generateManifestEntries() {
332                         HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
333
334                         /* first, create an index.html. */
335                         manifestEntries.put("index.html", manifestCreator.createManifestElement(
336                                         "index.html", "text/html; charset=utf-8",
337                                         "/templates/insert/index.html"));
338
339                         /* now, store the sone. */
340                         manifestEntries.put("sone.xml", manifestCreator.createManifestElement(
341                                         "sone.xml", "text/xml; charset=utf-8",
342                                         "/templates/insert/sone.xml"));
343
344                         return manifestEntries;
345                 }
346
347         }
348
349         /**
350          * Creates manifest elements for an insert by rendering a template.
351          *
352          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
353          */
354         @VisibleForTesting
355         static class ManifestCreator {
356
357                 private final Core core;
358                 private final Map<String, Object> soneProperties;
359
360                 ManifestCreator(Core core, Map<String, Object> soneProperties) {
361                         this.core = core;
362                         this.soneProperties = soneProperties;
363                 }
364
365                 public ManifestElement createManifestElement(String name, String contentType, String templateName) {
366                         InputStreamReader templateInputStreamReader = null;
367                         InputStream templateInputStream = null;
368                         Template template;
369                         try {
370                                 templateInputStream = getClass().getResourceAsStream(templateName);
371                                 templateInputStreamReader = new InputStreamReader(templateInputStream, utf8Charset);
372                                 template = TemplateParser.parse(templateInputStreamReader);
373                         } catch (TemplateException te1) {
374                                 logger.log(Level.SEVERE, String.format("Could not parse template “%s”!", templateName), te1);
375                                 return null;
376                         } finally {
377                                 Closer.close(templateInputStreamReader);
378                                 Closer.close(templateInputStream);
379                         }
380
381                         TemplateContext templateContext = templateContextFactory.createTemplateContext();
382                         templateContext.set("core", core);
383                         templateContext.set("currentSone", soneProperties);
384                         templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
385                         templateContext.set("version", SonePlugin.VERSION);
386                         StringWriter writer = new StringWriter();
387                         StringBucket bucket = null;
388                         try {
389                                 template.render(templateContext, writer);
390                                 bucket = new StringBucket(writer.toString(), utf8Charset);
391                                 return new ManifestElement(name, bucket, contentType, bucket.size());
392                         } catch (TemplateException te1) {
393                                 logger.log(Level.SEVERE, String.format("Could not render template “%s”!", templateName), te1);
394                                 return null;
395                         } finally {
396                                 Closer.close(writer);
397                                 if (bucket != null) {
398                                         bucket.free();
399                                 }
400                         }
401                 }
402
403         }
404
405 }