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